<template>
  <div class="admin-dashboard">
    <!-- 欢迎信息 -->
    <div class="welcome-card">
      <!-- 左侧区域：用户信息和统计 -->
      <div class="welcome-left">
        <!-- 头像和问候 -->
        <div class="user-greeting">
          <div class="user-avatar">
            <el-avatar
              :size="56"
              :src="userStore.avatar || '/default-avatar.png'"
            />
          </div>
          <div class="welcome-info">
            <div class="welcome-greeting">
              <div>{{ getGreeting() }}</div>
              <div class="date">{{ currentDate }}</div>
            </div>
          </div>
        </div>

        <!-- 统计数据 -->
        <div class="stat-items">
          <div class="stat-item">
            <div class="stat-label">今日任务</div>
            <div class="stat-value">4/8</div>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <div class="stat-label">通知</div>
            <div class="stat-value">2</div>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <div class="stat-label">项目</div>
            <div class="stat-value">12</div>
          </div>
        </div>
      </div>

      <!-- 中间区域：天气预报 -->
      <div class="weather-section">
        <div class="weather-container">
          <div class="weather-icon">
            <i class="fas fa-sun"></i>
          </div>
          <div class="weather-info">
            <div class="city-temp">
              <span class="city">贵港市</span>
              <span class="temperature">28°C</span>
            </div>
            <div class="forecast-row">
              <span
                v-for="(item, index) in weatherForecast"
                :key="index"
                class="day-forecast"
              >
                <span class="day">{{ item.day }}</span>
                <i :class="item.icon"></i>
                <span class="temp">{{ item.temp }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧区域：操作按钮 -->
      <div class="action-area">
        <el-button class="action-button" plain @click="refreshData">
          <i class="fas fa-sync"></i> 刷新数据
        </el-button>
        <el-button class="action-button" plain @click="exportData">
          <i class="fas fa-download"></i> 导出报表
        </el-button>
      </div>
    </div>

    <!-- 数据概览卡片 - 调整顺序和数据 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="(card, index) in statisticsCards" :key="index">
        <el-card
          class="statistics-card"
          :body-style="{ padding: '20px' }"
          shadow="hover"
          :style="getCardStyle(index)"
        >
          <div class="card-content">
            <div class="card-main">
              <div class="card-title">{{ card.title }}</div>
              <div class="card-value" :style="{ color: card.textColor }">
                {{ card.value }}
              </div>
              <div
                class="card-trend"
                :class="{ up: card.trend > 0, down: card.trend < 0 }"
              >
                <i
                  :class="
                    card.trend > 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'
                  "
                ></i>
                {{ Math.abs(card.trend) }}%
                {{ card.trend > 0 ? "增长" : "下降" }}
              </div>
            </div>
            <div
              class="card-icon"
              :style="{
                backgroundColor: card.iconBgColor,
                color: card.textColor,
              }"
            >
              <i :class="card.icon"></i>
            </div>
          </div>
          <div class="card-footer">
            <div class="footer-label">{{ card.footerLabel }}</div>
            <div class="footer-value" :style="{ color: card.textColor }">
              {{ card.footerValue }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主内容区和侧边栏布局 -->
    <el-row :gutter="20" class="mt-4">
      <!-- 主内容区 -->
      <el-col :span="18">
        <!-- 数据趋势区 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <div class="header-left">
                    <span class="title">营业额分析</span>
                    <el-tag type="success" effect="plain" class="ml-2">
                      同比增长 23.4%
                    </el-tag>
                  </div>
                  <div class="header-right">
                    <el-select
                      v-model="revenueAnalysisType"
                      size="small"
                      style="width: 120px"
                    >
                      <el-option label="全部数据" value="all" />
                      <el-option label="景点门票" value="ticket" />
                      <el-option label="酒店住宿" value="hotel" />
                    </el-select>
                  </div>
                </div>
              </template>
              <div ref="revenueAnalysisChartRef" style="height: 400px"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 内容分析区 -->
        <el-row :gutter="20" class="mt-4">
          <el-col :span="24">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <div class="header-left">
                    <span class="title">订单分析</span>
                    <el-tag type="primary" effect="plain" class="ml-2">
                      订单总量: 12,345
                    </el-tag>
                  </div>
                  <div class="header-right">
                    <el-radio-group v-model="orderAnalysisType" size="small">
                      <el-radio-button label="distribution"
                        >时段分布</el-radio-button
                      >
                      <el-radio-button label="trend">趋势分析</el-radio-button>
                    </el-radio-group>
                  </div>
                </div>
              </template>
              <div ref="orderDistributionChartRef" style="height: 400px"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 用户分析区 -->
        <el-row :gutter="20" class="mt-4">
          <!-- 用户画像 -->
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="title">用户画像分析</span>
                  <el-radio-group v-model="userAnalysisType" size="small">
                    <el-radio-button label="age">年龄分布</el-radio-button>
                    <el-radio-button label="gender">性别比例</el-radio-button>
                    <el-radio-button label="preference"
                      >偏好分析</el-radio-button
                    >
                  </el-radio-group>
                </div>
              </template>
              <div ref="userPortraitChartRef" style="height: 300px"></div>
            </el-card>
          </el-col>

          <!-- 业务指标分析 -->
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <div class="header-left">
                    <span class="title">业务指标分析</span>
                    <el-tag type="warning" effect="plain" class="ml-2">
                      综合评分: 85分
                    </el-tag>
                  </div>
                  <div class="header-right">
                    <el-radio-group v-model="businessMetricType" size="small">
                      <el-radio-button label="overall"
                        >整体指标</el-radio-button
                      >
                      <el-radio-button label="category"
                        >分类指标</el-radio-button
                      >
                    </el-radio-group>
                  </div>
                </div>
              </template>
              <div ref="businessMetricChartRef" style="height: 300px"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 用户数据概览区 -->
        <el-row :gutter="20" class="mt-4">
          <el-col :span="6" v-for="(item, index) in 4" :key="index">
            <el-card shadow="hover" class="data-overview-card">
              <div class="overview-header">
                <div class="overview-title">
                  {{
                    index === 0
                      ? "用户留存趋势"
                      : index === 1
                        ? "用户留存量"
                        : index === 2
                          ? "内容消费趋势"
                          : "内容消费量"
                  }}
                </div>
                <div class="overview-value">
                  <span class="number">{{
                    index === 0
                      ? "1,340"
                      : index === 1
                        ? "2,380"
                        : index === 2
                          ? "1,936"
                          : "1,647"
                  }}</span>
                  <span
                    class="trend"
                    :class="{
                      up: index === 0 || index === 2,
                      down: index === 1 || index === 3,
                    }"
                  >
                    <i
                      :class="
                        index === 0 || index === 2
                          ? 'fas fa-arrow-up'
                          : 'fas fa-arrow-down'
                      "
                    ></i>
                    {{
                      index === 0
                        ? "53.12%"
                        : index === 1
                          ? "44.12%"
                          : index === 2
                            ? "58.77%"
                            : "30.38%"
                    }}
                  </span>
                </div>
              </div>
              <div
                class="overview-chart"
                :ref="
                  index === 0
                    ? 'userRetentionTrendRef'
                    : index === 1
                      ? 'userRetentionVolumeRef'
                      : index === 2
                        ? 'contentConsumptionTrendRef'
                        : 'contentConsumptionVolumeRef'
                "
              ></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 地域分布区 -->
        <el-row :gutter="20" class="mt-4">
          <el-col :span="24">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="title">用户地域分布</span>
                  <el-select
                    v-model="regionType"
                    size="small"
                    style="width: 120px"
                  >
                    <el-option label="全国分布" value="china" />
                    <el-option label="广西分布" value="guangxi" />
                  </el-select>
                </div>
              </template>
              <div class="chart-wrapper">
                <div
                  id="region-map"
                  ref="regionMapChartRef"
                  style="height: 500px"
                ></div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 系统监控区 -->
        <el-row :gutter="20" class="mt-4">
          <el-col :span="24">
            <!-- 实时监控已移至侧边栏 -->
          </el-col>
        </el-row>
      </el-col>

      <!-- 侧边栏 -->
      <el-col :span="6">
        <!-- 待办任务区 -->
        <el-card shadow="hover" class="sidebar-card">
          <template #header>
            <div class="card-header">
              <span class="title">待办任务</span>
              <el-button
                type="primary"
                size="small"
                plain
                @click="showAddTaskDialog"
              >
                <el-icon><Plus /></el-icon> 新建任务
              </el-button>
            </div>
          </template>
          <div class="workspace-content">
            <!-- 待办任务列表 -->
            <div class="todo-list">
              <div class="section-header">
                <span class="section-stats">
                  <el-tag size="small" type="danger">{{
                    todoTasks.filter((task) => !task.completed).length
                  }}</el-tag>
                  <span class="ml-1">待处理</span>
                </span>
                <el-dropdown trigger="click" @command="handleTodoCommand">
                  <span class="el-dropdown-link">
                    <el-icon><More /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="all"
                        >全部任务</el-dropdown-item
                      >
                      <el-dropdown-item command="pending"
                        >待办任务</el-dropdown-item
                      >
                      <el-dropdown-item command="completed"
                        >已完成</el-dropdown-item
                      >
                      <el-dropdown-item divided command="clear"
                        >清除已完成</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <el-scrollbar height="250px">
                <el-empty
                  v-if="displayTodoTasks.length === 0"
                  description="暂无待办任务"
                />
                <div
                  v-else
                  v-for="(task, index) in displayTodoTasks"
                  :key="index"
                  class="todo-item"
                >
                  <div class="todo-item-left">
                    <el-checkbox
                      v-model="task.completed"
                      @change="handleTaskStatusChange(task)"
                    ></el-checkbox>
                    <div
                      class="todo-info"
                      :class="{ completed: task.completed }"
                    >
                      <div class="todo-title">{{ task.title }}</div>
                      <div class="todo-meta">
                        <el-tag
                          size="small"
                          :type="getPriorityType(task.priority)"
                          >{{ task.priority }}</el-tag
                        >
                        <span class="todo-deadline">{{ task.deadline }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="todo-actions">
                    <el-dropdown
                      trigger="click"
                      @command="
                        (command) => handleTaskAction(command, task, index)
                      "
                    >
                      <el-button type="text" size="small">
                        <el-icon><More /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="edit"
                            >编辑</el-dropdown-item
                          >
                          <el-dropdown-item command="delete" divided
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </el-card>

        <!-- 日程安排区 -->
        <el-card shadow="hover" class="sidebar-card mt-4">
          <template #header>
            <div class="card-header">
              <span class="title">日程安排</span>
              <el-button
                type="primary"
                size="small"
                plain
                @click="showAddEventDialog"
              >
                <el-icon><Plus /></el-icon> 新建日程
              </el-button>
            </div>
          </template>
          <div class="workspace-content">
            <!-- 简易日历 -->
            <div class="calendar-header">
              <el-date-picker
                v-model="selectedDate"
                type="date"
                format="YYYY/MM/DD"
                placeholder="选择日期"
                :disabled-date="disabledDate"
                @change="handleDateChange"
              />
            </div>

            <!-- 当日事件列表 -->
            <div class="calendar-events mt-3">
              <div class="section-header">
                <span class="today-date">{{
                  formatDate(selectedDate || new Date())
                }}</span>
                <el-dropdown trigger="click" @command="handleCalendarCommand">
                  <span class="el-dropdown-link">
                    <el-icon><More /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="day">日视图</el-dropdown-item>
                      <el-dropdown-item command="week">周视图</el-dropdown-item>
                      <el-dropdown-item command="month"
                        >月视图</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <el-scrollbar height="180px">
                <el-empty
                  v-if="filteredCalendarEvents.length === 0"
                  description="暂无日程安排"
                />
                <div
                  v-else
                  v-for="(event, index) in filteredCalendarEvents"
                  :key="index"
                  class="calendar-event"
                >
                  <div class="event-time">
                    <el-icon><Clock /></el-icon>
                    <span>{{ event.time }}</span>
                  </div>
                  <div class="event-content">
                    <div class="event-title">{{ event.title }}</div>
                    <div class="event-location" v-if="event.location">
                      <el-icon><Location /></el-icon>
                      <span>{{ event.location }}</span>
                    </div>
                  </div>
                  <div class="event-actions">
                    <el-dropdown
                      trigger="click"
                      @command="
                        (command) => handleEventAction(command, event, index)
                      "
                    >
                      <el-button type="text" size="small">
                        <el-icon><More /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="edit"
                            >编辑</el-dropdown-item
                          >
                          <el-dropdown-item command="delete" divided
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                  <div
                    class="event-indicator"
                    :style="{ backgroundColor: event.color }"
                  ></div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </el-card>

        <!-- AI智能助手 -->
        <el-card shadow="hover" class="sidebar-card mt-4">
          <template #header>
            <div class="card-header">
              <span class="title">AI智能助手</span>
              <el-switch
                v-model="aiAssistantEnabled"
                size="small"
                active-color="#13ce66"
              ></el-switch>
            </div>
          </template>
          <div class="workspace-content">
            <div class="assistant-container" v-if="aiAssistantEnabled">
              <div class="assistant-avatar">
                <el-avatar :size="40" class="assistant-icon">
                  <el-icon><ChatDotRound /></el-icon>
                </el-avatar>
              </div>
              <div class="assistant-content">
                <div
                  class="assistant-message"
                  v-if="!isAnalyzing && aiResponse"
                >
                  <div class="ai-response-container">
                    <pre class="ai-response-text">{{ aiResponse }}</pre>
                  </div>
                </div>
                <div class="assistant-message" v-else-if="isAnalyzing">
                  <el-skeleton :rows="3" animated />
                </div>
                <div class="assistant-message" v-else>
                  点击下方按钮，AI将自动分析当前页面数据并提供见解
                </div>
                <div class="assistant-actions mt-2">
                  <el-button
                    type="primary"
                    size="small"
                    :loading="isAnalyzing"
                    @click="generateAIAnalysis"
                    :disabled="isAnalyzing"
                  >
                    {{ isAnalyzing ? "分析中..." : "生成分析" }}
                  </el-button>
                  <el-button
                    type="info"
                    size="small"
                    plain
                    @click="handleAIHelp"
                  >
                    <el-icon><Question /></el-icon> 帮助
                  </el-button>
                </div>
              </div>
            </div>
            <el-empty v-else description="AI助手已关闭" />
          </div>
        </el-card>

        <!-- 实时监控区 -->
        <el-card shadow="hover" class="sidebar-card mt-4">
          <template #header>
            <div class="card-header">
              <span class="title">实时监控</span>
              <el-button
                type="primary"
                size="small"
                plain
                @click="refreshMonitorData"
              >
                <el-icon><Refresh /></el-icon> 刷新
              </el-button>
            </div>
          </template>
          <div class="workspace-content">
            <div class="sidebar-monitor-stats">
              <div class="stat-item">
                <span class="label">在线用户</span>
                <span class="value">{{ monitorStats.onlineUsers }}</span>
              </div>
              <div class="stat-item">
                <span class="label">CPU使用率</span>
                <el-progress
                  :percentage="monitorStats.cpuUsage"
                  :color="getCpuUsageColor"
                  :format="(val) => val + '%'"
                  class="inline-progress"
                />
              </div>
              <div class="stat-item">
                <span class="label">内存使用率</span>
                <el-progress
                  :percentage="monitorStats.memoryUsage"
                  :color="getMemoryUsageColor"
                  :format="(val) => val + '%'"
                  class="inline-progress"
                />
              </div>
              <div class="stat-item">
                <span class="label">今日访问量</span>
                <span class="value">{{
                  monitorStats.todayVisits || "1,286"
                }}</span>
              </div>
              <div class="stat-item">
                <span class="label">系统运行时间</span>
                <span class="value">{{ monitorStats.uptime }}</span>
              </div>
            </div>

            <div class="sidebar-monitor-logs mt-3">
              <div class="section-header">
                <span>系统日志</span>
                <el-button type="text" size="small" @click="refreshLogs">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
              <el-scrollbar height="200px">
                <div
                  v-for="(log, index) in monitorLogs.slice(0, 5)"
                  :key="index"
                  class="log-item"
                >
                  <div class="log-header">
                    <span class="log-time">{{ log.timestamp }}</span>
                    <el-tag size="small" :type="getMonitorLogType(log.type)">{{
                      log.type
                    }}</el-tag>
                  </div>
                  <div class="log-content">
                    <div class="log-user">{{ log.user }} ({{ log.ip }})</div>
                    <div class="log-action">{{ log.action }}</div>
                    <el-tag
                      size="small"
                      :type="log.status === 'success' ? 'success' : 'danger'"
                    >
                      {{ log.status === "success" ? "成功" : "失败" }}
                    </el-tag>
                  </div>
                </div>
                <div class="view-more-link" v-if="monitorLogs.length > 5">
                  <el-link type="primary" @click="showAllLogs"
                    >查看全部日志</el-link
                  >
                </div>
              </el-scrollbar>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加任务对话框 -->
    <el-dialog
      v-model="taskDialogVisible"
      :title="isEditingTask ? '编辑任务' : '新建任务'"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="taskForm"
        label-width="80px"
        :rules="taskRules"
        ref="taskFormRef"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="taskForm.title"
            placeholder="请输入任务标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select
            v-model="taskForm.priority"
            placeholder="请选择优先级"
            style="width: 100%"
          >
            <el-option label="高" value="高"></el-option>
            <el-option label="中" value="中"></el-option>
            <el-option label="低" value="低"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期" prop="deadlineDate">
          <el-date-picker
            v-model="taskForm.deadlineDate"
            type="datetime"
            placeholder="选择日期和时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入任务描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="taskDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitTaskForm"
            :loading="taskSubmitting"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 添加日程对话框 -->
    <el-dialog
      v-model="eventDialogVisible"
      :title="isEditingEvent ? '编辑日程' : '新建日程'"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="eventForm"
        label-width="80px"
        :rules="eventRules"
        ref="eventFormRef"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="eventForm.title"
            placeholder="请输入日程标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="eventForm.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="时间" prop="startTime">
          <el-time-select
            v-model="eventForm.startTime"
            start="08:00"
            step="00:30"
            end="22:00"
            placeholder="开始时间"
            style="width: 47%"
          ></el-time-select>
          <span class="mx-2">至</span>
          <el-time-select
            v-model="eventForm.endTime"
            start="08:00"
            step="00:30"
            end="22:00"
            placeholder="结束时间"
            style="width: 47%"
            :min-time="eventForm.startTime"
          ></el-time-select>
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input
            v-model="eventForm.location"
            placeholder="请输入地点"
          ></el-input>
        </el-form-item>
        <el-form-item label="颜色标记">
          <el-color-picker v-model="eventForm.color"></el-color-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="eventForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="eventDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitEventForm"
            :loading="eventSubmitting"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  computed,
  watch,
  onUnmounted,
  nextTick,
  reactive,
} from "vue";
import * as echarts from "echarts";
import "echarts-extension-amap";
import { useUserStore } from "@/stores/user";
import {
  Plus,
  More,
  Clock,
  Location,
  Question,
  ChatDotRound,
  Refresh,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "@/api/axios"; // 导入axios实例
import { analyzeWithDeepseek, registerStreamCallback, unregisterStreamCallback } from '@/utils/deepseekAI.js'; // 导入deepseekAI模块
import axios from "@/api/axios";

const userStore = useUserStore();

// 获取用户信息方法
const fetchUserInfo = async () => {
  try {
    const response = await service.get("/admin/profile");
    if (response && response.data) {
      // 如果后端返回了数据，更新userStore
      userStore.setUserInfo({
        ...userStore.userInfo,
        username: response.data.username || response.data.nickname || response.data.name,
        avatar: response.data.avatar
      });
    }
  } catch (error) {
    console.log("获取用户信息失败，使用本地数据", error);
    // 如果出错，就保持使用现有的测试数据，不需要提示用户
  }
};

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo();
  initWeatherForecast();
  // 其他onMounted代码...
});

// 当前日期和问候语
const currentDate = new Date().toLocaleDateString("zh-CN", {
  year: "numeric",
  month: "long",
  day: "numeric",
  weekday: "long",
});

// 天气图标映射
const weatherIcons = {
  sunny: "fas fa-sun",
  partlyCloudy: "fas fa-cloud-sun",
  cloudy: "fas fa-cloud",
  rainy: "fas fa-cloud-showers-heavy",
  thunderstorm: "fas fa-bolt",
  snow: "fas fa-snowflake",
  foggy: "fas fa-smog"
};

// 天气预报数据
const weatherForecast = ref([]);

// 初始化天气预报数据
const initWeatherForecast = async () => {
  try {
    // 贵港市的经纬度坐标
    const latitude = 23.1135; // 贵港市纬度
    const longitude = 110.2964; // 贵港市经度
    
    // 使用Open-Meteo API获取天气数据
    const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&daily=weathercode,temperature_2m_max,temperature_2m_min&current_weather=true&timezone=Asia/Shanghai&forecast_days=4`);
    
    const data = await response.json();
    console.log("管理面板天气API响应:", data);
    
    if (data && data.current_weather && data.daily) {
      const forecast = [];
      const today = new Date();
      const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      
      // 获取当前温度和天气代码
      const currentTemp = Math.round(data.current_weather.temperature);
      const currentWeatherCode = data.current_weather.weathercode;
      
      // 添加今天的天气
      forecast.push({
        day: "今天",
        icon: getIconByWeatherCode(currentWeatherCode),
        temp: `${currentTemp}°C`
      });
      
      // 添加未来3天的天气预报
      for (let i = 1; i < Math.min(4, data.daily.time.length); i++) {
        const forecastDate = new Date(data.daily.time[i]);
        const dayIndex = forecastDate.getDay(); // 0-6
        const forecastCode = data.daily.weathercode[i];
        const maxTemp = Math.round(data.daily.temperature_2m_max[i]);
        
        forecast.push({
          day: weekdays[dayIndex],
          icon: getIconByWeatherCode(forecastCode),
          temp: `${maxTemp}°C`
        });
      }
      
      weatherForecast.value = forecast;
    } else {
      // 如果API调用失败，使用默认数据
      generateDefaultWeatherForecast();
    }
  } catch (error) {
    console.error("获取天气数据失败:", error);
    // 使用默认数据
    generateDefaultWeatherForecast();
  }
};

// 根据天气代码获取对应的图标
const getIconByWeatherCode = (code) => {
  // WMO天气代码对照表：https://www.nodc.noaa.gov/archive/arc0021/0002199/1.1/data/0-data/HTML/WMO-CODE/WMO4677.HTM
  if (code === 0 || code === 1) { // 晴朗
    return weatherIcons.sunny;
  } else if (code === 2) { // 局部多云
    return weatherIcons.partlyCloudy;
  } else if (code === 3 || code === 45 || code === 48) { // 多云或雾
    return weatherIcons.cloudy;
  } else if ([51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 80, 81, 82].includes(code)) { // 各种雨
    return weatherIcons.rainy;
  } else if ([95, 96, 99].includes(code)) { // 雷暴
    return weatherIcons.thunderstorm;
  } else if ([71, 73, 75, 77, 85, 86].includes(code)) { // 各种雪
    return weatherIcons.snow;
  } else {
    return weatherIcons.sunny; // 默认为晴天
  }
};

// 生成默认的天气预报数据（备用）
const generateDefaultWeatherForecast = () => {
  const today = new Date();
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  
  // 随机天气条件和温度
  const weatherConditions = [
    { icon: weatherIcons.sunny, minTemp: 25, maxTemp: 30 },
    { icon: weatherIcons.partlyCloudy, minTemp: 22, maxTemp: 28 },
    { icon: weatherIcons.cloudy, minTemp: 20, maxTemp: 25 },
    { icon: weatherIcons.rainy, minTemp: 18, maxTemp: 23 },
    { icon: weatherIcons.thunderstorm, minTemp: 17, maxTemp: 22 },
  ];
  
  const forecast = [];
  
  // 今天
  forecast.push({
    day: "今天",
    icon: weatherConditions[Math.floor(Math.random() * 3)].icon, // 偏向晴天和多云
    temp: `${Math.floor(Math.random() * 5) + 25}°C` // 25-30°C
  });
  
  // 接下来三天
  for (let i = 1; i <= 3; i++) {
    const nextDay = new Date(today);
    nextDay.setDate(today.getDate() + i);
    const dayIndex = nextDay.getDay(); // 0-6
    
    // 随机天气情况
    const condition = weatherConditions[Math.floor(Math.random() * weatherConditions.length)];
    const temp = `${Math.floor(Math.random() * (condition.maxTemp - condition.minTemp + 1)) + condition.minTemp}°C`;
    
    forecast.push({
      day: weekdays[dayIndex],
      icon: condition.icon,
      temp: temp
    });
  }
  
  weatherForecast.value = forecast;
};

const getGreeting = () => {
  const hour = new Date().getHours();
  let greeting = "";
  if (hour < 6) greeting = "凌晨好";
  else if (hour < 9) greeting = "早上好";
  else if (hour < 12) greeting = "上午好";
  else if (hour < 14) greeting = "中午好";
  else if (hour < 17) greeting = "下午好";
  else if (hour < 19) greeting = "傍晚好";
  else greeting = "晚上好";
  
  // 添加用户名到问候语
  return greeting + (userStore.username ? `！${userStore.username}` : "");
};

// 调整统计卡片数据顺序和内容
const statisticsCards = ref([
  {
    title: "今日营业额",
    value: "¥32,860",
    trend: 15.4,
    icon: "fas fa-yuan-sign",
    bgColor: "linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%)",
    textColor: "#1890ff",
    iconBgColor: "rgba(24, 144, 255, 0.1)",
    footerLabel: "日均收入",
    footerValue: "¥1,234",
  },
  {
    title: "今日订单数",
    value: "386",
    trend: 8.2,
    icon: "fas fa-shopping-cart",
    bgColor: "linear-gradient(135deg, #f6ffed 0%, #b7eb8f 100%)",
    textColor: "#52c41a",
    iconBgColor: "rgba(82, 196, 26, 0.1)",
    footerLabel: "日均订单量",
    footerValue: "386",
  },
  {
    title: "今日访问量",
    value: "2,384",
    trend: 12.5,
    icon: "fas fa-users",
    bgColor: "linear-gradient(135deg, #f9f0ff 0%, #d3adf7 100%)",
    textColor: "#722ed1",
    iconBgColor: "rgba(114, 46, 209, 0.1)",
    footerLabel: "日均访问量",
    footerValue: "2,384",
  },
  {
    title: "转化率",
    value: "28.5%",
    trend: 5.8,
    icon: "fas fa-percentage",
    bgColor: "linear-gradient(135deg, #fff7e6 0%, #ffd591 100%)",
    textColor: "#faad14",
    iconBgColor: "rgba(250, 173, 20, 0.1)",
    footerLabel: "平均转化率",
    footerValue: "28.5%",
  },
]);

// 获取卡片背景样式
const getCardStyle = (index) => {
  return {
    background: statisticsCards.value[index].bgColor,
  };
};

// 热门景点数据
const hotSpots = ref([
  {
    id: 1,
    name: "象鼻山",
    image: "https://example.com/spot1.jpg",
    visits: "12,345",
    orders: "1,234",
    trend: 15,
  },
  {
    id: 2,
    name: "七星公园",
    image: "https://example.com/spot2.jpg",
    visits: "10,234",
    orders: "987",
    trend: 8,
  },
  {
    id: 3,
    name: "独秀峰",
    image: "https://example.com/spot3.jpg",
    visits: "9,876",
    orders: "876",
    trend: -5,
  },
  {
    id: 4,
    name: "叠彩山",
    image: "https://example.com/spot4.jpg",
    visits: "8,765",
    orders: "765",
    trend: 12,
  },
  {
    id: 5,
    name: "芦笛岩",
    image: "https://example.com/spot5.jpg",
    visits: "7,654",
    orders: "654",
    trend: 6,
  },
]);

// 系统通知数据
const systemNotifications = ref([
  {
    title: "系统升级通知",
    content: "系统将于今晚22:00进行例行维护升级",
    timestamp: "2024-03-01 10:00:00",
    type: "warning",
    color: "#E6A23C",
    read: false,
    hollow: true,
  },
  {
    title: "新增商家入驻申请",
    content: "新增3家商家入驻申请待审核",
    timestamp: "2024-03-01 09:30:00",
    type: "success",
    color: "#67C23A",
    read: false,
    hollow: true,
  },
  {
    title: "安全警告",
    content: "发现异常登录行为，请及时查看",
    timestamp: "2024-03-01 09:00:00",
    type: "danger",
    color: "#F56C6C",
    read: true,
    hollow: false,
  },
]);

// 未读通知计数
const hasUnreadNotifications = computed(() => {
  return systemNotifications.value.some((notification) => !notification.read);
});

const unreadCount = computed(() => {
  return systemNotifications.value.filter((notification) => !notification.read)
    .length;
});

// 监控统计数据
const monitorStats = ref({
  onlineUsers: 1234,
  cpuUsage: 45,
  memoryUsage: 62,
  uptime: "23天15小时",
});

// 监控日志数据
const monitorLogs = ref([
  {
    timestamp: "2024-03-01 10:00:00",
    type: "login",
    ip: "192.168.1.100",
    user: "admin",
    action: "登录系统",
    status: "success",
  },
  {
    timestamp: "2024-03-01 09:58:23",
    type: "operation",
    ip: "192.168.1.101",
    user: "operator1",
    action: "修改系统配置",
    status: "success",
  },
  {
    timestamp: "2024-03-01 09:55:12",
    type: "warning",
    ip: "192.168.1.102",
    user: "unknown",
    action: "尝试访问未授权资源",
    status: "failed",
  },
]);

// 获取监控日志类型样式
const getMonitorLogType = (type) => {
  const typeMap = {
    login: "primary",
    operation: "success",
    warning: "warning",
    error: "danger",
  };
  return typeMap[type] || "info";
};

// 图表实例
let userPortraitChart = null;
let map = ref(null); // 保持这个为ref，因为代码中使用了map.value
let userRetentionTrendChart = null;
let userRetentionVolumeChart = null;
let contentConsumptionTrendChart = null;
let contentConsumptionVolumeChart = null;
let orderDistributionChart = null;
let revenueAnalysisChart = null;
let businessMetricChart = null;
let performanceChart = null;
let visitsChart = null;
let salesTrendChart = null;

// 添加 ref
const performanceChartRef = ref(null);
const visitsChartRef = ref(null);
const userPortraitChartRef = ref(null);
const salesTrendChartRef = ref(null);

// 监控相关
const monitorActiveTab = ref("logs");

// 获取CPU使用率颜色
const getCpuUsageColor = (percentage) => {
  if (percentage < 60) return "#67C23A";
  if (percentage < 80) return "#E6A23C";
  return "#F56C6C";
};

// 获取内存使用率颜色
const getMemoryUsageColor = (percentage) => {
  if (percentage < 60) return "#67C23A";
  if (percentage < 80) return "#E6A23C";
  return "#F56C6C";
};

// 用户画像分析
const userAnalysisType = ref("age");

// 地域分布
const regionType = ref("china");
const regionMapChartRef = ref(null);

// 订单分析
const orderAnalysisType = ref("distribution");
const orderDistributionChartRef = ref(null);

// 用户数据概览图表引用
const userRetentionTrendRef = ref(null);
const userRetentionVolumeRef = ref(null);
const contentConsumptionTrendRef = ref(null);
const contentConsumptionVolumeRef = ref(null);

// 营业额分析
const revenueAnalysisType = ref("all");
const revenueAnalysisChartRef = ref(null);

// 业务指标分析
const businessMetricType = ref("overall");
const businessMetricChartRef = ref(null);

// 刷新数据
const refreshData = () => {
  // TODO: 实现数据刷新逻辑
};

// 导出数据
const exportData = () => {
  ElMessageBox.confirm(
    "您想要导出哪类数据？",
    "导出数据",
    {
      confirmButtonText: "全部数据",
      cancelButtonText: "取消",
      distinguishCancelAndClose: true,
      type: "info",
    }
  )
    .then(async () => {
      try {
        // 请求生成Excel文件
        const response = await axios.get('/admin/export', {
          responseType: 'blob'
        });
        
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `dashboard-export-${new Date().toISOString().split('T')[0]}.xlsx`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        ElMessage({
          type: 'success',
          message: '数据导出成功'
        });
      } catch (error) {
        console.error('导出数据失败:', error);
        ElMessage.error('导出数据失败，请重试');
      }
    })
    .catch((action) => {
      // 用户取消
      if (action === 'cancel') {
        ElMessage({
          type: 'info',
          message: '已取消导出'
        });
      }
    });
};

onMounted(() => {
  try {
    // 初始化时立即更新主题
    updateChartTheme();

    // 注册地图数据
    (async () => {
      try {
        // 使用 china geo json 数据
        const chinaResponse = await fetch(
          "https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json",
        );
        const chinaJson = await chinaResponse.json();
        echarts.registerMap("china", chinaJson);

        // 使用广西 geo json 数据
        const guangxiResponse = await fetch(
          "https://geo.datav.aliyun.com/areas_v3/bound/450000_full.json",
        );
        const guangxiJson = await guangxiResponse.json();
        echarts.registerMap("guangxi", guangxiJson);
      } catch (error) {
        console.error("加载地图数据失败:", error);
      }
    })();

    // 确保DOM已经渲染
    setTimeout(() => {
      try {
        // 初始化性能监控图表
        if (performanceChartRef.value) {
          performanceChart = echarts.init(performanceChartRef.value);
          performanceChart.setOption({
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "cross",
                label: {
                  backgroundColor: "#6a7985",
                },
              },
              backgroundColor: "rgba(255, 255, 255, 0.8)",
              borderColor: "#eee",
              borderWidth: 1,
              textStyle: {
                color: "#333",
              },
              extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
            },
            legend: {
              data: ["CPU使用率", "内存使用率", "磁盘I/O"],
              icon: "roundRect",
              itemWidth: 12,
              itemHeight: 6,
              right: 10,
              top: 0,
            },
            grid: {
              left: "3%",
              right: "4%",
              bottom: "3%",
              top: "40px",
              containLabel: true,
            },
            xAxis: {
              type: "category",
              boundaryGap: false,
              data: [
                "12:00",
                "13:00",
                "14:00",
                "15:00",
                "16:00",
                "17:00",
                "现在",
              ],
              axisLine: {
                lineStyle: {
                  color: "#909399",
                },
              },
              axisTick: {
                alignWithLabel: true,
              },
            },
            yAxis: {
              type: "value",
              max: 100,
              axisLabel: {
                formatter: "{value}%",
              },
              splitLine: {
                lineStyle: {
                  type: "dashed",
                },
              },
            },
            series: [
              {
                name: "CPU使用率",
                type: "line",
                smooth: true,
                showSymbol: false,
                emphasis: {
                  focus: "series",
                },
                lineStyle: {
                  width: 3,
                },
                areaStyle: {
                  opacity: 0.2,
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: "rgba(64, 158, 255, 0.8)",
                    },
                    {
                      offset: 1,
                      color: "rgba(64, 158, 255, 0.1)",
                    },
                  ]),
                },
                data: [45, 42, 47, 44, 43, 45, 45],
                itemStyle: { color: "#409EFF" },
                animationDuration: 2000,
                animationEasing: "cubicInOut",
              },
              {
                name: "内存使用率",
                type: "line",
                smooth: true,
                showSymbol: false,
                emphasis: {
                  focus: "series",
                },
                lineStyle: {
                  width: 3,
                },
                areaStyle: {
                  opacity: 0.2,
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: "rgba(103, 194, 58, 0.8)",
                    },
                    {
                      offset: 1,
                      color: "rgba(103, 194, 58, 0.1)",
                    },
                  ]),
                },
                data: [62, 58, 65, 62, 60, 62, 62],
                itemStyle: { color: "#67C23A" },
                animationDuration: 2000,
                animationEasing: "cubicInOut",
                animationDelay: 300,
              },
              {
                name: "磁盘I/O",
                type: "line",
                smooth: true,
                showSymbol: false,
                emphasis: {
                  focus: "series",
                },
                lineStyle: {
                  width: 3,
                },
                areaStyle: {
                  opacity: 0.2,
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: "rgba(230, 162, 60, 0.8)",
                    },
                    {
                      offset: 1,
                      color: "rgba(230, 162, 60, 0.1)",
                    },
                  ]),
                },
                data: [30, 28, 35, 32, 34, 31, 33],
                itemStyle: { color: "#E6A23C" },
                animationDuration: 2000,
                animationEasing: "cubicInOut",
                animationDelay: 600,
              },
            ],
          });
        }

        // 初始化访问统计图表
        if (visitsChartRef.value) {
          visitsChart = echarts.init(visitsChartRef.value);
          visitsChart.setOption({
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "shadow",
              },
              backgroundColor: "rgba(255, 255, 255, 0.8)",
              borderColor: "#eee",
              borderWidth: 1,
              textStyle: {
                color: "#333",
              },
              extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
            },
            legend: {
              data: ["访问量", "独立访客"],
              icon: "roundRect",
              itemWidth: 12,
              itemHeight: 6,
              right: 10,
              top: 0,
            },
            grid: {
              left: "3%",
              right: "4%",
              bottom: "3%",
              top: "40px",
              containLabel: true,
            },
            xAxis: {
              type: "category",
              data: [
                "12:00",
                "13:00",
                "14:00",
                "15:00",
                "16:00",
                "17:00",
                "现在",
              ],
              axisLine: {
                lineStyle: {
                  color: "#909399",
                },
              },
              axisTick: {
                alignWithLabel: true,
              },
            },
            yAxis: {
              type: "value",
              splitLine: {
                lineStyle: {
                  type: "dashed",
                },
              },
            },
            series: [
              {
                name: "访问量",
                type: "bar",
                barWidth: "40%",
                stack: "total",
                emphasis: {
                  focus: "series",
                },
                data: [1200, 1350, 1400, 1300, 1450, 1380, 1420],
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#409EFF" },
                    { offset: 1, color: "#69c0ff" },
                  ]),
                  borderRadius: [4, 4, 0, 0],
                },
                animationDuration: 2000,
                animationDelay: function (idx) {
                  return idx * 100;
                },
              },
              {
                name: "独立访客",
                type: "bar",
                barWidth: "40%",
                stack: "total",
                emphasis: {
                  focus: "series",
                },
                data: [800, 900, 950, 880, 970, 920, 950],
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#67C23A" },
                    { offset: 1, color: "#95de64" },
                  ]),
                  borderRadius: [4, 4, 0, 0],
                },
                animationDuration: 2000,
                animationDelay: function (idx) {
                  return idx * 100 + 100;
                },
              },
            ],
          });
        }

        // 初始化用户画像图表
        if (userPortraitChartRef.value) {
          userPortraitChart = echarts.init(userPortraitChartRef.value);
          updateUserPortraitChart();
        }

        // 初始化地域分布图表
        updateRegionMap();

        // 初始化用户数据概览图表
        initOverviewCharts();

        // 初始化订单分布图表
        if (orderDistributionChartRef.value) {
          orderDistributionChart = echarts.init(
            orderDistributionChartRef.value,
          );
          updateOrderDistributionChart();
        }

        // 初始化营业额分析图表
        if (revenueAnalysisChartRef.value) {
          revenueAnalysisChart = echarts.init(revenueAnalysisChartRef.value);
          updateRevenueAnalysisChart();
        }

        // 初始化业务指标图表
        if (businessMetricChartRef.value) {
          businessMetricChart = echarts.init(businessMetricChartRef.value);
          updateBusinessMetricChart();
        }

        // 定义 handleResize 函数
        const handleResize = () => {
          try {
            // 调整所有图表大小
            Object.values(chartInstances).forEach((chart) => {
              if (chart && !chart.isDisposed()) {
                chart.resize();
              }
            });
          } catch (error) {
            console.error("调整图表大小时出错:", error);
          }
        };

        // 监听窗口大小变化
        window.addEventListener("resize", handleResize);

        // 在组件卸载时移除事件监听器
        onUnmounted(() => {
          window.removeEventListener("resize", handleResize);
        });
      } catch (error) {
        console.error("初始化图表时出错:", error);
      }
    }, 300);

    // 使用 MutationObserver 监听主题变化
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.attributeName === "class") {
          updateChartTheme();
        }
      });
    });

    // 监听 HTML 根元素的 class 变化
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["class"],
    });

    // 在组件卸载时清理 observer
    onUnmounted(() => {
      observer.disconnect();
    });

    // 初始化侧边栏中的监控图表
    nextTick(() => {
      if (sidebarPerformanceChartRef.value) {
        sidebarPerformanceChart = echarts.init(
          sidebarPerformanceChartRef.value,
        );
        updatePerformanceChart(sidebarPerformanceChart, true);
      }

      if (sidebarVisitsChartRef.value) {
        sidebarVisitsChart = echarts.init(sidebarVisitsChartRef.value);
        updateVisitsChart(sidebarVisitsChart, true);
      }
    });

    // 加载待办任务和日程安排数据
    loadTodoTasks();
    loadCalendarEvents();
  } catch (error) {
    console.error("初始化图表时出错:", error);
  }
});

// 修改图表主题配置
const updateChartTheme = () => {
  try {
    const isDark = document.documentElement.classList.contains("dark");
    // 确保在非暗黑模式下使用黑色文字
    const textColor = isDark ? "#FFFFFF" : "#303133";
    const axisLineColor = isDark ? "#4C4D4F" : "#E4E7ED";
    const splitLineColor = isDark ? "rgba(255, 255, 255, 0.1)" : "#E4E7ED";

    console.log(
      "Theme updated:",
      isDark ? "dark" : "light",
      "textColor:",
      textColor,
    ); // 添加调试日志

    const baseChartOption = {
      textStyle: {
        color: textColor,
      },
      title: {
        textStyle: {
          color: textColor,
        },
      },
      legend: {
        textStyle: {
          color: textColor,
        },
      },
      xAxis: {
        axisLine: {
          lineStyle: {
            color: axisLineColor,
          },
        },
        axisLabel: {
          color: textColor,
        },
        splitLine: {
          lineStyle: {
            color: splitLineColor,
          },
        },
      },
      yAxis: {
        axisLine: {
          lineStyle: {
            color: axisLineColor,
          },
        },
        axisLabel: {
          color: textColor,
        },
        splitLine: {
          lineStyle: {
            color: splitLineColor,
          },
        },
        nameTextStyle: {
          color: textColor,
        },
      },
      tooltip: {
        backgroundColor: isDark
          ? "rgba(30, 30, 30, 0.9)"
          : "rgba(255, 255, 255, 0.9)",
        borderColor: isDark ? "#434343" : "#E4E7ED",
        textStyle: {
          color: textColor,
        },
      },
    };

    // 更新所有图表主题
    [
      performanceChart,
      visitsChart,
      userPortraitChart,
      salesTrendChart,
      orderDistributionChart,
      userRetentionTrendChart,
      userRetentionVolumeChart,
      contentConsumptionTrendChart,
      contentConsumptionVolumeChart,
      revenueAnalysisChart,
      businessMetricChart,
    ].forEach((chart) => {
      if (chart && !chart.isDisposed()) {
        try {
          const currentOption = chart.getOption();
          const newOption = {
            ...baseChartOption,
            ...currentOption,
          };

          // 深度合并图例配置
          if (currentOption.legend) {
            newOption.legend = {
              ...currentOption.legend,
              textStyle: {
                ...currentOption.legend?.textStyle,
                color: textColor,
              },
              // 确保图例中每个项的文字颜色都更新
              data: currentOption.legend.data?.map((item) => {
                if (typeof item === "string") {
                  return item;
                }
                return {
                  ...item,
                  textStyle: {
                    ...item?.textStyle,
                    color: textColor,
                  },
                };
              }),
            };
          }

          // 如果是饼图，更新标签颜色
          if (currentOption.series?.[0]?.type === "pie") {
            newOption.series = currentOption.series.map((series) => ({
              ...series,
              label: {
                ...series.label,
                color: textColor,
              },
              // 更新饼图图例文字颜色
              data: series.data?.map((item) => ({
                ...item,
                label: {
                  ...item.label,
                  color: textColor,
                },
              })),
            }));
          }

          // 如果是雷达图，更新指示器文字颜色
          if (currentOption.radar) {
            newOption.radar = {
              ...currentOption.radar,
              axisName: {
                ...currentOption.radar?.axisName,
                color: textColor,
              },
              splitLine: {
                lineStyle: {
                  color: splitLineColor,
                },
              },
              axisLine: {
                lineStyle: {
                  color: axisLineColor,
                },
              },
              // 确保雷达图的指示器文字颜色更新
              indicator: currentOption.radar.indicator?.map((item) => ({
                ...item,
                color: textColor,
              })),
            };
          }

          chart.setOption(newOption, true); // 使用 true 参数强制更新
        } catch (error) {
          console.error("更新图表主题时出错:", error);
        }
      }
    });

    // 更新地域分布图表
    if (map.value && !map.value.isDisposed()) {
      try {
        const regionOption = map.value.getOption();
        const newRegionOption = {
          ...baseChartOption,
          ...regionOption,
          series: regionOption.series.map((series) => ({
            ...series,
            label: {
              ...series.label,
              color: textColor,
            },
          })),
        };

        // 确保地图图例文字颜色更新
        if (newRegionOption.legend) {
          newRegionOption.legend.textStyle = {
            ...newRegionOption.legend.textStyle,
            color: textColor,
          };
        }

        map.value.setOption(newRegionOption, true); // 使用 true 参数强制更新
      } catch (error) {
        console.error("更新地域图表主题时出错:", error);
      }
    }
  } catch (error) {
    console.error("更新图表主题时出错:", error);
  }
};

// 更新用户画像图表
const updateUserPortraitChart = () => {
  try {
    if (!userPortraitChartRef.value) return;

    if (userPortraitChart) {
      userPortraitChart.dispose();
    }

    userPortraitChart = echarts.init(userPortraitChartRef.value);
    chartInstances.userPortraitChart = userPortraitChart; // 存储图表实例

    const options = {
      age: {
        title: {
          text: "用户年龄分布",
          left: "center",
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c}% ({d}%)",
          backgroundColor: "rgba(255, 255, 255, 0.8)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
        },
        legend: {
          orient: "horizontal",
          bottom: 10,
          left: "center",
          icon: "circle",
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 15,
          textStyle: {
            fontSize: 12,
          },
          selectedMode: true,
        },
        series: [
          {
            type: "pie",
            radius: ["35%", "60%"],
            center: ["50%", "45%"],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 6,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: "bold",
                formatter: "{b}\n{c}%",
              },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.2)",
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              {
                value: 20,
                name: "18岁以下",
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#ff9a9e" },
                    { offset: 1, color: "#fad0c4" },
                  ]),
                },
              },
              {
                value: 35,
                name: "18-25岁",
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#a1c4fd" },
                    { offset: 1, color: "#c2e9fb" },
                  ]),
                },
              },
              {
                value: 25,
                name: "26-35岁",
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#84fab0" },
                    { offset: 1, color: "#8fd3f4" },
                  ]),
                },
              },
              {
                value: 15,
                name: "36-45岁",
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#fccb90" },
                    { offset: 1, color: "#d57eeb" },
                  ]),
                },
              },
              {
                value: 5,
                name: "45岁以上",
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#e0c3fc" },
                    { offset: 1, color: "#8ec5fc" },
                  ]),
                },
              },
            ],
            animationType: "scale",
            animationEasing: "elasticOut",
            animationDelay: function (idx) {
              return Math.random() * 200;
            },
          },
        ],
      },
      gender: {
        title: {
          text: "用户性别比例",
          left: "center",
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c}% ({d}%)",
          backgroundColor: "rgba(255, 255, 255, 0.8)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
        },
        legend: {
          orient: "horizontal",
          bottom: 10,
          left: "center",
          icon: "circle",
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 20,
          textStyle: {
            fontSize: 12,
          },
        },
        series: [
          {
            type: "pie",
            radius: ["35%", "60%"],
            center: ["50%", "45%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 6,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: true,
              position: "inside",
              formatter: "{d}%",
              fontSize: 14,
              fontWeight: "bold",
              color: "#fff",
            },
            labelLine: {
              show: false,
            },
            data: [
              {
                value: 45,
                name: "男性",
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#4facfe" },
                    { offset: 1, color: "#00f2fe" },
                  ]),
                },
              },
              {
                value: 55,
                name: "女性",
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#ff9a9e" },
                    { offset: 1, color: "#fad0c4" },
                  ]),
                },
              },
            ],
            animationType: "scale",
            animationEasing: "elasticOut",
            animationDelay: function (idx) {
              return Math.random() * 200;
            },
          },
        ],
      },
      preference: {
        title: {
          text: "内容主题分布",
          left: "center",
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "item",
          backgroundColor: "rgba(255, 255, 255, 0.8)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
        },
        legend: {
          data: ["纯文本", "图文类", "视频类"],
          bottom: 5,
          left: "center",
          icon: "circle",
          itemWidth: 8,
          itemHeight: 8,
          itemGap: 15,
        },
        radar: {
          indicator: [
            { name: "国际", max: 100 },
            { name: "娱乐", max: 100 },
            { name: "纯文本", max: 100 },
            { name: "图文类", max: 100 },
            { name: "视频类", max: 100 },
            { name: "体育", max: 100 },
            { name: "科技", max: 100 },
            { name: "财经", max: 100 },
          ],
          radius: "65%",
          center: ["50%", "50%"],
          splitNumber: 4,
          shape: "polygon",
          name: {
            formatter: function (value) {
              return "{a|" + value + "}";
            },
            rich: {
              a: {
                color: "var(--el-text-color-primary)",
                fontSize: 14,
                fontWeight: "bold",
                padding: [3, 5],
              },
            },
          },
          splitArea: {
            areaStyle: {
              color: [
                "rgba(255, 255, 255, 0.03)",
                "rgba(255, 255, 255, 0.05)",
                "rgba(255, 255, 255, 0.07)",
                "rgba(255, 255, 255, 0.09)",
              ],
            },
          },
          axisLine: {
            lineStyle: {
              color: "rgba(211, 211, 211, 0.3)",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(211, 211, 211, 0.3)",
            },
          },
        },
        series: [
          {
            name: "纯文本",
            type: "radar",
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
              width: 2,
              color: "#5470c6",
            },
            areaStyle: {
              color: "rgba(84, 112, 198, 0.2)",
            },
            data: [
              {
                value: [80, 70, 90, 60, 50, 75, 65, 85],
                name: "纯文本",
                itemStyle: {
                  color: "#5470c6",
                },
              },
            ],
          },
          {
            name: "图文类",
            type: "radar",
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
              width: 2,
              color: "#91cc75",
            },
            areaStyle: {
              color: "rgba(145, 204, 117, 0.2)",
            },
            data: [
              {
                value: [70, 80, 60, 85, 65, 90, 75, 60],
                name: "图文类",
                itemStyle: {
                  color: "#91cc75",
                },
              },
            ],
          },
          {
            name: "视频类",
            type: "radar",
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
              width: 2,
              color: "#fac858",
            },
            areaStyle: {
              color: "rgba(250, 200, 88, 0.2)",
            },
            data: [
              {
                value: [60, 75, 65, 70, 90, 80, 85, 55],
                name: "视频类",
                itemStyle: {
                  color: "#fac858",
                },
              },
            ],
          },
        ],
        animationDuration: 2000,
        animationEasing: "cubicInOut",
      },
    };

    if (options[userAnalysisType.value]) {
      userPortraitChart.setOption(options[userAnalysisType.value]);
    }
  } catch (error) {
    console.error("更新用户画像图表时出错:", error);
  }
};

// 地图配置参数 - 直接在代码中设置好，不需要用户调整
const mapConfig = reactive({
  china: {
    zoom: 1.2,
    layoutCenter: [500, 350], // 调整中国地图的中心位置
    layoutSize: 700, // 调整中国地图的大小
  },
  guangxi: {
    zoom: 1.1,
    layoutCenter: [400, 250],
    layoutSize: 450,
  },
});

// 更新地域分布图表
const updateRegionMap = async () => {
  try {
    if (!regionMapChartRef.value) return;

    if (map.value) {
      // 如果图表已经存在，先销毁它
      map.value.dispose();
    }

    // 添加延迟，确保DOM元素已完全渲染
    await nextTick();

    const chart = echarts.init(regionMapChartRef.value);
    map.value = chart; // 保存地图实例引用
    chartInstances.regionMap = chart; // 存储图表实例

    // 根据选择的类型显示不同的数据
    const regionData = {
      china: {
        data: [
          { name: "广西壮族自治区", value: 890 },
          { name: "广东省", value: 450 },
          { name: "湖南省", value: 300 },
          { name: "云南省", value: 200 },
          { name: "贵州省", value: 150 },
          { name: "四川省", value: 280 },
          { name: "江西省", value: 220 },
          { name: "福建省", value: 260 },
          { name: "浙江省", value: 380 },
          { name: "江苏省", value: 340 },
          { name: "上海市", value: 420 },
          { name: "北京市", value: 400 },
        ],
        title: "全国用户分布",
      },
      guangxi: {
        data: [
          { name: "贵港市", value: 520 },
          { name: "南宁市", value: 370 },
          { name: "桂林市", value: 280 },
          { name: "柳州市", value: 190 },
          { name: "北海市", value: 150 },
          { name: "玉林市", value: 120 },
          { name: "钦州市", value: 110 },
          { name: "梧州市", value: 100 },
          { name: "防城港市", value: 90 },
          { name: "百色市", value: 85 },
          { name: "河池市", value: 80 },
          { name: "贺州市", value: 75 },
          { name: "来宾市", value: 70 },
          { name: "崇左市", value: 65 },
        ],
        title: "广西用户分布",
      },
    };

    const selectedData = regionData[regionType.value];

    // 计算最大值和最小值
    const values = selectedData.data.map((item) => item.value);
    const maxValue = Math.max(...values);
    const minValue = Math.min(...values);

    const option = {
      title: {
        text: selectedData.title,
        left: "center",
        top: 10,
        textStyle: {
          fontSize: 16,
          fontWeight: "normal",
        },
      },
      tooltip: {
        trigger: "item",
        formatter: function (params) {
          const item = selectedData.data.find((d) => d.name === params.name);
          if (item) {
            return `${params.name}<br/>用户数量: ${item.value.toLocaleString()} 人`;
          }
          return params.name;
        },
        backgroundColor: "rgba(255, 255, 255, 0.9)",
        borderColor: "#f2f3f5",
        borderWidth: 1,
        textStyle: {
          color: "#1d2129",
        },
      },
      visualMap: {
        type: "continuous",
        min: minValue,
        max: maxValue,
        text: ["高", "低"],
        realtime: false,
        calculable: true,
        inRange: {
          color: ["#C6E5FF", "#409EFF", "#2B7ADF", "#0D5EFF"],
        },
        textStyle: {
          color: "#4e5969",
        },
        left: "left",
        bottom: 10,
        formatter: function (value) {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + "w";
          } else if (value >= 1000) {
            return (value / 1000).toFixed(1) + "k";
          }
          return value;
        },
      },
      geo: {
        map: regionType.value,
        roam: true, // 允许缩放和平移，便于用户调整
        zoom: mapConfig[regionType.value].zoom, // 使用配置的缩放比例
        label: {
          show: true,
          fontSize: regionType.value === "china" ? 8 : 10, // 全国地图字体小一点
          color: "#333",
        },
        emphasis: {
          label: {
            show: true,
            color: "#fff",
            fontSize: regionType.value === "china" ? 10 : 12,
            fontWeight: "bold",
          },
          itemStyle: {
            areaColor: "#0D5EFF",
            borderWidth: 1,
          },
        },
        itemStyle: {
          borderColor: "#fff",
          borderWidth: 1,
          areaColor: "#f3f4f5",
        },
        // 使用配置的地图位置和大小
        layoutCenter: mapConfig[regionType.value].layoutCenter,
        layoutSize: mapConfig[regionType.value].layoutSize,
        // 禁止选择区域
        selectedMode: false,
      },
      series: [
        {
          name: "用户数量",
          type: "map",
          geoIndex: 0,
          data: selectedData.data.map((item) => {
            return {
              name: item.name,
              value: item.value,
            };
          }),
        },
      ],
    };

    chart.setOption(option);

    // 添加延迟后再次调整大小，确保正确渲染
    setTimeout(() => {
      if (chart && !chart.isDisposed()) {
        chart.resize();
      }
    }, 100);
  } catch (error) {
    console.error("初始化地域图表时出错:", error);
  }
};

// 初始化用户数据概览图表
const initOverviewCharts = () => {
  try {
    // 用户留存趋势 - 折线图
    if (userRetentionTrendRef.value) {
      userRetentionTrendChart = echarts.init(userRetentionTrendRef.value);
      chartInstances.userRetentionTrendChart = userRetentionTrendChart; // 存储图表实例
      userRetentionTrendChart.setOption({
        grid: {
          top: 0,
          right: 0,
          bottom: 0,
          left: 0,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          show: false,
        },
        yAxis: {
          type: "value",
          show: false,
        },
        series: [
          {
            data: [50, 65, 55, 80, 45, 65, 75, 50, 80, 75],
            type: "line",
            smooth: true,
            symbol: "none",
            lineStyle: {
              width: 3,
              color: "#409EFF",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
                { offset: 1, color: "rgba(64, 158, 255, 0.1)" },
              ]),
            },
          },
        ],
        animation: false,
      });
    }

    // 用户留存量 - 柱状图
    if (userRetentionVolumeRef.value) {
      userRetentionVolumeChart = echarts.init(userRetentionVolumeRef.value);
      chartInstances.userRetentionVolumeChart = userRetentionVolumeChart; // 存储图表实例
      userRetentionVolumeChart.setOption({
        grid: {
          top: 0,
          right: 0,
          bottom: 0,
          left: 0,
        },
        xAxis: {
          type: "category",
          show: false,
        },
        yAxis: {
          type: "value",
          show: false,
        },
        series: [
          {
            data: [
              { value: 35, itemStyle: { color: "#67C23A" } },
              { value: 40, itemStyle: { color: "#409EFF" } },
              { value: 35, itemStyle: { color: "#67C23A" } },
              { value: 38, itemStyle: { color: "#409EFF" } },
              { value: 45, itemStyle: { color: "#67C23A" } },
              { value: 42, itemStyle: { color: "#409EFF" } },
              { value: 50, itemStyle: { color: "#67C23A" } },
              { value: 48, itemStyle: { color: "#409EFF" } },
              { value: 52, itemStyle: { color: "#67C23A" } },
              { value: 50, itemStyle: { color: "#409EFF" } },
            ],
            type: "bar",
            barWidth: "60%",
          },
        ],
        animation: false,
      });
    }

    // 内容消费趋势 - 折线图
    if (contentConsumptionTrendRef.value) {
      contentConsumptionTrendChart = echarts.init(
        contentConsumptionTrendRef.value,
      );
      chartInstances.contentConsumptionTrendChart =
        contentConsumptionTrendChart; // 存储图表实例
      contentConsumptionTrendChart.setOption({
        grid: {
          top: 0,
          right: 0,
          bottom: 0,
          left: 0,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          show: false,
        },
        yAxis: {
          type: "value",
          show: false,
        },
        series: [
          {
            data: [60, 75, 65, 55, 70, 65, 55, 60, 75, 65],
            type: "line",
            smooth: true,
            symbol: "none",
            lineStyle: {
              width: 3,
              color: "#E6A23C",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(230, 162, 60, 0.3)" },
                { offset: 1, color: "rgba(230, 162, 60, 0.1)" },
              ]),
            },
          },
        ],
        animation: false,
      });
    }

    // 内容消费量 - 柱状图
    if (contentConsumptionVolumeRef.value) {
      contentConsumptionVolumeChart = echarts.init(
        contentConsumptionVolumeRef.value,
      );
      chartInstances.contentConsumptionVolumeChart =
        contentConsumptionVolumeChart; // 存储图表实例
      contentConsumptionVolumeChart.setOption({
        grid: {
          top: 0,
          right: 0,
          bottom: 0,
          left: 0,
        },
        xAxis: {
          type: "category",
          show: false,
        },
        yAxis: {
          type: "value",
          show: false,
        },
        series: [
          {
            data: [
              { value: 45, itemStyle: { color: "#67C23A" } },
              { value: 38, itemStyle: { color: "#409EFF" } },
              { value: 42, itemStyle: { color: "#67C23A" } },
              { value: 40, itemStyle: { color: "#409EFF" } },
              { value: 35, itemStyle: { color: "#67C23A" } },
              { value: 38, itemStyle: { color: "#409EFF" } },
              { value: 30, itemStyle: { color: "#67C23A" } },
              { value: 35, itemStyle: { color: "#409EFF" } },
              { value: 42, itemStyle: { color: "#67C23A" } },
              { value: 40, itemStyle: { color: "#409EFF" } },
            ],
            type: "bar",
            barWidth: "60%",
          },
        ],
        animation: false,
      });
    }
  } catch (error) {
    console.error("初始化用户数据概览图表时出错:", error);
  }
};

// 更新订单分布图表
const updateOrderDistributionChart = () => {
  try {
    if (!orderDistributionChartRef.value || !orderDistributionChart) return;

    // 存储图表实例
    chartInstances.orderDistributionChart = orderDistributionChart;

    if (orderAnalysisType.value === "distribution") {
      // 时段分布
      orderDistributionChart.setOption({
        title: {
          text: "订单发布比例",
          left: "left",
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params) {
            let result = params[0].name + "<br/>";
            let total = 0;
            params.forEach((item) => {
              total += item.value;
              result +=
                item.marker +
                " " +
                item.seriesName +
                ": " +
                item.value +
                "<br/>";
            });
            result +=
              '<div style="margin-top:5px;border-top:1px solid #eee;padding-top:5px;">';
            result += "总计: " + total;
            result += "</div>";
            return result;
          },
          backgroundColor: "rgba(255, 255, 255, 0.8)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
        },
        legend: {
          data: ["景点门票", "酒店住宿", "文创商品"],
          right: 10,
          top: 0,
          icon: "circle",
          itemWidth: 8,
          itemHeight: 8,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "60px",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: [
            "0:00",
            "2:00",
            "4:00",
            "6:00",
            "8:00",
            "10:00",
            "12:00",
            "14:00",
            "16:00",
            "18:00",
            "20:00",
            "22:00",
          ],
          axisLine: {
            lineStyle: {
              color: "#909399",
            },
          },
          axisTick: {
            alignWithLabel: true,
          },
        },
        yAxis: {
          type: "value",
          name: "订单数量",
          nameTextStyle: {
            padding: [0, 0, 0, 40],
          },
          splitLine: {
            lineStyle: {
              type: "dashed",
            },
          },
          axisLabel: {
            formatter: function (value) {
              if (value >= 1000) {
                return value / 1000 + "k";
              }
              return value;
            },
          },
        },
        series: [
          {
            name: "景点门票",
            type: "bar",
            stack: "total",
            emphasis: {
              focus: "series",
            },
            barWidth: "60%",
            data: [
              1200, 2800, 1400, 2000, 1500, 1800, 1200, 2000, 2200, 1800, 2400,
              2000,
            ],
            itemStyle: {
              color: "#5470c6",
            },
          },
          {
            name: "酒店住宿",
            type: "bar",
            stack: "total",
            emphasis: {
              focus: "series",
            },
            data: [
              1500, 1200, 1000, 2500, 2800, 2600, 2800, 1600, 1400, 1200, 1000,
              800,
            ],
            itemStyle: {
              color: "#91cc75",
            },
          },
          {
            name: "文创商品",
            type: "bar",
            stack: "total",
            emphasis: {
              focus: "series",
            },
            data: [
              1800, 2800, 2000, 3000, 1000, 2200, 2000, 2600, 2800, 1600, 1800,
              1000,
            ],
            itemStyle: {
              color: "#fac858",
            },
          },
        ],
        animationDuration: 2000,
        animationEasing: "cubicInOut",
      });
    } else {
      // 趋势分析 - 堆叠面积图
      orderDistributionChart.setOption({
        title: {
          text: "订单时段分析",
          left: "left",
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
          backgroundColor: "rgba(255, 255, 255, 0.8)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
        },
        legend: {
          data: ["景点门票", "酒店住宿", "文创商品"],
          right: 10,
          top: 0,
          icon: "circle",
          itemWidth: 8,
          itemHeight: 8,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "60px",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [
            "0:00",
            "2:00",
            "4:00",
            "6:00",
            "8:00",
            "10:00",
            "12:00",
            "14:00",
            "16:00",
            "18:00",
            "20:00",
            "22:00",
          ],
          axisLine: {
            lineStyle: {
              color: "#909399",
            },
          },
        },
        yAxis: {
          type: "value",
          name: "百分比",
          nameTextStyle: {
            padding: [0, 0, 0, 40],
          },
          min: 20,
          max: 100,
          splitLine: {
            lineStyle: {
              type: "dashed",
            },
          },
          axisLabel: {
            formatter: "{value}%",
          },
        },
        series: [
          {
            name: "景点门票",
            type: "line",
            stack: "Total",
            smooth: true,
            lineStyle: {
              width: 0,
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(84, 112, 198, 0.8)",
                },
                {
                  offset: 1,
                  color: "rgba(84, 112, 198, 0.3)",
                },
              ]),
            },
            emphasis: {
              focus: "series",
            },
            data: [80, 60, 55, 60, 85, 70, 35, 40, 50, 80, 85, 80],
          },
          {
            name: "酒店住宿",
            type: "line",
            stack: "Total",
            smooth: true,
            lineStyle: {
              width: 0,
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(145, 204, 117, 0.8)",
                },
                {
                  offset: 1,
                  color: "rgba(145, 204, 117, 0.3)",
                },
              ]),
            },
            emphasis: {
              focus: "series",
            },
            data: [30, 40, 60, 70, 50, 60, 70, 60, 40, 50, 60, 55],
          },
          {
            name: "文创商品",
            type: "line",
            stack: "Total",
            smooth: true,
            lineStyle: {
              width: 0,
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(250, 200, 88, 0.8)",
                },
                {
                  offset: 1,
                  color: "rgba(250, 200, 88, 0.3)",
                },
              ]),
            },
            emphasis: {
              focus: "series",
            },
            data: [50, 55, 45, 50, 65, 55, 45, 60, 70, 40, 50, 55],
          },
        ],
        animationDuration: 2000,
        animationEasing: "cubicInOut",
      });
    }
  } catch (error) {
    console.error("更新订单分布图表时出错:", error);
  }
};

// 更新营业额分析图表
const updateRevenueAnalysisChart = () => {
  try {
    if (!revenueAnalysisChartRef.value || !revenueAnalysisChart) return;

    // 存储图表实例
    chartInstances.revenueAnalysisChart = revenueAnalysisChart;

    const dates = [
      "12.10",
      "12.11",
      "12.12",
      "12.13",
      "12.14",
      "12.15",
      "12.16",
      "12.17",
    ];

    let series = [];
    let legend = [];

    if (
      revenueAnalysisType.value === "all" ||
      revenueAnalysisType.value === "ticket"
    ) {
      series.push({
        name: "景点门票",
        type: "line",
        smooth: true,
        symbol: "none",
        lineStyle: {
          width: 3,
          color: "#5470c6",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(84, 112, 198, 0.5)" },
            { offset: 1, color: "rgba(84, 112, 198, 0.1)" },
          ]),
        },
        emphasis: {
          focus: "series",
        },
        z: 9,
        data: [21000, 19000, 17000, 19000, 21000, 15000, 13000, 23000],
      });

      legend.push("景点门票");
    }

    if (
      revenueAnalysisType.value === "all" ||
      revenueAnalysisType.value === "hotel"
    ) {
      series.push({
        name: "酒店住宿",
        type: "line",
        smooth: true,
        symbol: "none",
        lineStyle: {
          width: 3,
          color: "#91cc75",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(145, 204, 117, 0.5)" },
            { offset: 1, color: "rgba(145, 204, 117, 0.1)" },
          ]),
        },
        emphasis: {
          focus: "series",
        },
        z: 8,
        data: [9000, 9000, 9000, 9000, 9000, 9000, 9000, 15000],
      });

      legend.push("酒店住宿");
    }

    revenueAnalysisChart.setOption({
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: "#6a7985",
          },
        },
        formatter: function (params) {
          let result = params[0].name + "<br/>";
          params.forEach((item) => {
            result +=
              item.marker +
              " " +
              item.seriesName +
              ": ¥" +
              item.value +
              "<br/>";
          });
          return result;
        },
        backgroundColor: "rgba(255, 255, 255, 0.8)",
        borderColor: "#eee",
        borderWidth: 1,
        textStyle: {
          color: "#333",
        },
        extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
      },
      legend: {
        data: legend,
        right: 10,
        top: 0,
        icon: "roundRect",
        itemWidth: 12,
        itemHeight: 6,
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        top: "40px",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: dates,
        axisLine: {
          lineStyle: {
            color: "#909399",
          },
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: [
        {
          type: "value",
          name: "营业额",
          min: 0,
          max: 30000,
          interval: 5000,
          position: "left",
          axisLine: {
            show: true,
            lineStyle: {
              color: "#5470c6",
            },
          },
          axisLabel: {
            formatter: function (value) {
              if (value === 0) {
                return "0";
              } else if (value >= 1000) {
                return "¥" + value / 1000 + "k";
              }
              return "¥" + value;
            },
          },
          splitLine: {
            lineStyle: {
              type: "dashed",
            },
          },
        },
      ],
      series: series,
      animationDuration: 2000,
      animationEasing: "cubicInOut",
    });
  } catch (error) {
    console.error("更新营业额分析图表时出错:", error);
  }
};

// 更新业务指标图表
const updateBusinessMetricChart = () => {
  try {
    if (!businessMetricChart || !businessMetricChartRef.value) return;

    // 存储图表实例
    chartInstances.businessMetricChart = businessMetricChart;

    if (businessMetricType.value === "overall") {
      // 整体指标 - 单个六角雷达图
      businessMetricChart.setOption({
        title: {
          text: "", // 删除"业务整体指标分析"标题
          left: "center",
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "item",
          backgroundColor: "rgba(255, 255, 255, 0.8)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
          formatter: function (params) {
            const indicator = params.indicator;
            const indicatorInfo =
              params.name === "当前值"
                ? businessMetricChart.getOption().radar[0].indicator[indicator]
                : null;

            let html = params.marker + " " + params.name + ": " + params.value;
            if (indicatorInfo && indicatorInfo.desc) {
              html +=
                '<br/><span style="color:#999;font-size:12px;margin-left:16px;">' +
                indicatorInfo.desc +
                "</span>";
            }
            return html;
          },
        },
        legend: {
          data: ["当前值", "目标值"],
          bottom: 0,
          left: "center",
          icon: "roundRect",
          itemWidth: 12,
          itemHeight: 6,
          itemGap: 20,
        },
        radar: {
          indicator: [
            { name: "销售业绩", max: 100, desc: "景区门票、酒店和商品销售额" },
            { name: "用户满意度", max: 100, desc: "用户评分和反馈" },
            { name: "市场占有率", max: 100, desc: "在贵港文旅市场的份额" },
            { name: "增长趋势", max: 100, desc: "环比和同比增长率" },
            { name: "用户留存", max: 100, desc: "回访率和复购率" },
            { name: "运营效率", max: 100, desc: "成本控制和资源利用率" },
          ],
          radius: "65%",
          center: ["50%", "55%"],
          shape: "polygon",
          splitNumber: 4,
          axisName: {
            formatter: function (value, indicator) {
              return "{title|" + value + "}\n{detail|" + indicator.desc + "}";
            },
            rich: {
              title: {
                color: "#333",
                fontSize: 14,
                fontWeight: "bold",
                lineHeight: 20,
              },
              detail: {
                color: "#666",
                fontSize: 10,
                lineHeight: 14,
                width: 80,
                align: "center",
              },
            },
            padding: [10, 10, 10, 10],
            show: true,
          },
          splitArea: {
            areaStyle: {
              color: [
                "rgba(255, 255, 255, 0.03)",
                "rgba(255, 255, 255, 0.05)",
                "rgba(255, 255, 255, 0.07)",
                "rgba(255, 255, 255, 0.09)",
              ],
            },
          },
          axisLine: {
            lineStyle: {
              color: "rgba(211, 211, 211, 0.3)",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(211, 211, 211, 0.3)",
            },
          },
        },
        series: [
          {
            name: "业务指标",
            type: "radar",
            emphasis: {
              lineStyle: {
                width: 4,
              },
            },
            data: [
              {
                value: [85, 90, 75, 80, 70, 85],
                name: "当前值",
                symbol: "circle",
                symbolSize: 8,
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "rgba(64, 158, 255, 0.7)" },
                    { offset: 1, color: "rgba(64, 158, 255, 0.1)" },
                  ]),
                },
                lineStyle: {
                  color: "#409EFF",
                  width: 2,
                },
                itemStyle: {
                  color: "#409EFF",
                  borderColor: "#fff",
                  borderWidth: 2,
                },
              },
              {
                value: [90, 95, 85, 90, 80, 95],
                name: "目标值",
                symbol: "circle",
                symbolSize: 8,
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "rgba(230, 162, 60, 0.7)" },
                    { offset: 1, color: "rgba(230, 162, 60, 0.1)" },
                  ]),
                },
                lineStyle: {
                  color: "#E6A23C",
                  width: 2,
                  type: "dashed",
                },
                itemStyle: {
                  color: "#E6A23C",
                  borderColor: "#fff",
                  borderWidth: 2,
                },
              },
            ],
            animationDuration: 2000,
            animationEasing: "cubicInOut",
          },
        ],
      });
    } else {
      // 分类指标 - 多个六角雷达图
      businessMetricChart.setOption({
        title: {
          text: "", // 删除"业务分类指标分析"标题
          left: "center",
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "item",
          backgroundColor: "rgba(255, 255, 255, 0.8)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          extraCssText: "box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);",
          formatter: function (params) {
            const indicator = params.indicator;
            const indicatorInfo =
              businessMetricChart.getOption().radar[0].indicator[indicator];

            let html = params.marker + " " + params.name + ": " + params.value;
            if (indicatorInfo && indicatorInfo.desc) {
              html +=
                '<br/><span style="color:#999;font-size:12px;margin-left:16px;">' +
                indicatorInfo.desc +
                "</span>";
            }
            return html;
          },
        },
        legend: {
          data: ["景点门票", "酒店住宿", "文创商品"],
          bottom: 0,
          left: "center",
          icon: "roundRect",
          itemWidth: 12,
          itemHeight: 6,
          itemGap: 20,
        },
        radar: {
          indicator: [
            { name: "销售业绩", max: 100, desc: "景区门票、酒店和商品销售额" },
            { name: "用户满意度", max: 100, desc: "用户评分和反馈" },
            { name: "市场占有率", max: 100, desc: "在贵港文旅市场的份额" },
            { name: "增长趋势", max: 100, desc: "环比和同比增长率" },
            { name: "用户留存", max: 100, desc: "回访率和复购率" },
            { name: "运营效率", max: 100, desc: "成本控制和资源利用率" },
          ],
          radius: "65%",
          center: ["50%", "55%"],
          shape: "polygon",
          splitNumber: 4,
          name: {
            formatter: function (value) {
              return "{a|" + value + "}";
            },
            rich: {
              a: {
                color: "var(--el-text-color-primary)",
                fontSize: 14,
                fontWeight: "bold",
                padding: [3, 5],
              },
            },
          },
          splitArea: {
            areaStyle: {
              color: [
                "rgba(255, 255, 255, 0.03)",
                "rgba(255, 255, 255, 0.05)",
                "rgba(255, 255, 255, 0.07)",
                "rgba(255, 255, 255, 0.09)",
              ],
            },
          },
          axisLine: {
            lineStyle: {
              color: "rgba(211, 211, 211, 0.3)",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(211, 211, 211, 0.3)",
            },
          },
        },
        series: [
          {
            name: "业务指标",
            type: "radar",
            emphasis: {
              lineStyle: {
                width: 4,
              },
            },
            data: [
              {
                value: [90, 85, 80, 85, 75, 90],
                name: "景点门票",
                symbol: "circle",
                symbolSize: 8,
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "rgba(84, 112, 198, 0.7)" },
                    { offset: 1, color: "rgba(84, 112, 198, 0.1)" },
                  ]),
                },
                lineStyle: {
                  color: "#5470c6",
                  width: 2,
                },
                itemStyle: {
                  color: "#5470c6",
                  borderColor: "#fff",
                  borderWidth: 2,
                },
              },
              {
                value: [75, 90, 70, 80, 85, 75],
                name: "酒店住宿",
                symbol: "circle",
                symbolSize: 8,
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "rgba(145, 204, 117, 0.7)" },
                    { offset: 1, color: "rgba(145, 204, 117, 0.1)" },
                  ]),
                },
                lineStyle: {
                  color: "#91cc75",
                  width: 2,
                },
                itemStyle: {
                  color: "#91cc75",
                  borderColor: "#fff",
                  borderWidth: 2,
                },
              },
              {
                value: [80, 75, 85, 70, 80, 85],
                name: "文创商品",
                symbol: "circle",
                symbolSize: 8,
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "rgba(250, 200, 88, 0.7)" },
                    { offset: 1, color: "rgba(250, 200, 88, 0.1)" },
                  ]),
                },
                lineStyle: {
                  color: "#fac858",
                  width: 2,
                },
                itemStyle: {
                  color: "#fac858",
                  borderColor: "#fff",
                  borderWidth: 2,
                },
              },
            ],
            animationDuration: 2000,
            animationEasing: "cubicInOut",
          },
        ],
      });
    }
  } catch (error) {
    console.error("更新业务指标图表时出错:", error);
  }
};

// 监听用户画像类型变化
watch(userAnalysisType, () => {
  updateUserPortraitChart();
});

// 监听地域类型变化
watch(regionType, () => {
  updateRegionMap();
});

// 监听订单分析类型变化
watch(orderAnalysisType, () => {
  updateOrderDistributionChart();
});

// 监听营业额分析类型变化
watch(revenueAnalysisType, () => {
  updateRevenueAnalysisChart();
});

// 监听业务指标类型变化
watch(businessMetricType, () => {
  updateBusinessMetricChart();
});

// 个人工作区数据
const todoTasks = ref([
  {
    title: "完成贵港文旅平台月度报告",
    completed: false,
    priority: "高",
    deadline: "今天 18:00",
  },
  {
    title: "审核新增景点信息",
    completed: false,
    priority: "中",
    deadline: "明天 12:00",
  },
  {
    title: "参加营销策略会议",
    completed: false,
    priority: "高",
    deadline: "今天 14:30",
  },
  {
    title: "回复用户反馈邮件",
    completed: true,
    priority: "中",
    deadline: "昨天 16:00",
  },
  {
    title: "更新夏季促销活动内容",
    completed: false,
    priority: "低",
    deadline: "后天 10:00",
  },
]);

// 加载待办任务数据
const loadTodoTasks = async () => {
  try {
    const response = await axios.get("/admin/tasks");
    if (response && response.length > 0) {
      todoTasks.value = response;
    }
  } catch (error) {
    console.error("加载待办任务失败:", error);
    ElMessage.error("加载待办任务失败，使用本地数据");
    // 使用测试数据，已默认设置
  }
};

const calendarEvents = ref([
  {
    time: "09:30 - 10:30",
    title: "周一晨会",
    location: "线上会议室",
    color: "#1890ff",
  },
  {
    time: "12:00 - 13:30",
    title: "与景区负责人午餐会",
    location: "行政中心",
    color: "#52c41a",
  },
  {
    time: "14:30 - 16:00",
    title: "营销策略讨论",
    location: "会议室B",
    color: "#722ed1",
  },
  {
    time: "16:30 - 17:30",
    title: "系统更新评审",
    location: "技术部",
    color: "#fa8c16",
  },
]);

// 加载日程安排数据
const loadCalendarEvents = async () => {
  try {
    const response = await axios.get("/admin/calendar-events");
    if (response && response.length > 0) {
      calendarEvents.value = response;
    }
  } catch (error) {
    console.error("加载日程安排失败:", error);
    ElMessage.error("加载日程安排失败，使用本地数据");
    // 使用测试数据，已默认设置
  }
};

const aiAssistantEnabled = ref(true);
const aiResponse = ref("");
const isAnalyzing = ref(false);

// 生成AI分析
const generateAIAnalysis = async () => {
  try {
    isAnalyzing.value = true;
    aiResponse.value = ""; // 清空之前的响应

    // 收集当前页面数据
    const pageData = {
      statisticsCards: statisticsCards.value,
      hotSpots: hotSpots.value,
      systemNotifications: systemNotifications.value,
      monitorStats: monitorStats.value,
      weatherForecast: weatherForecast.value,
    };

    // 注册流式回调，实现逐字输出效果
    registerStreamCallback((newContent) => {
      // 移除调试日志，减少控制台输出
      aiResponse.value += newContent;
    });
    
    // 调用Deepseek R1模型API进行分析（流式调用）
    await analyzeWithDeepseek(pageData);
    
    // 分析完成后取消回调注册
    unregisterStreamCallback();
  } catch (error) {
    console.error("AI分析生成失败:", error);
    aiResponse.value = "抱歉，分析过程中出现错误，请稍后再试。";
  } finally {
    isAnalyzing.value = false;
  }
};

// 根据数据生成分析结果
const generateAnalysisFromData = (data) => {
  // 这个函数已不再使用，分析逻辑已移动到utils/deepseekAI.js文件中
  // 通过analyzeWithDeepseek方法进行调用
  return "此函数已弃用，请使用deepseekAI.analyzeWithDeepseek";
};

// 格式化日期
const formatDate = (date) => {
  return date.toLocaleDateString("zh-CN", {
    month: "long",
    day: "numeric",
  });
};

// 获取任务优先级对应的类型
const getPriorityType = (priority) => {
  switch (priority) {
    case "高":
      return "danger";
    case "中":
      return "warning";
    case "低":
      return "info";
    default:
      return "info";
  }
};

// 处理待办任务命令
const handleTodoCommand = (command) => {
  switch (command) {
    case "all":
      todoTaskFilter.value = "all";
      break;
    case "pending":
      todoTaskFilter.value = "pending";
      break;
    case "completed":
      todoTaskFilter.value = "completed";
      break;
    case "clear":
      ElMessageBox.confirm("确定要清除所有已完成的任务吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          todoTasks.value = todoTasks.value.filter((task) => !task.completed);
          ElMessage.success("已清除所有已完成任务");
        })
        .catch(() => {});
      break;
  }
};

// 处理任务状态变化
const handleTaskStatusChange = async (task) => {
  try {
    await axios.put(`/admin/tasks/${task.id}/status`, {
      completed: task.completed
    });
    
    ElMessage({
      message: task.completed ? "任务已完成" : "任务已恢复",
      type: "success",
    });
  } catch (error) {
    console.error("更新任务状态失败:", error);
    ElMessage.error("更新任务状态失败，请重试");
    // 回滚状态
    task.completed = !task.completed;
  }
};

// 处理任务操作
const handleTaskAction = async (command, task, index) => {
  if (command === "edit") {
    showEditTaskDialog(task, index);
  } else if (command === "delete") {
    ElMessageBox.confirm("确定要删除这个任务吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        try {
          if (task.id) {
            await axios.delete(`/admin/tasks/${task.id}`);
          }
          todoTasks.value.splice(index, 1);
          ElMessage.success("任务已删除");
        } catch (error) {
          console.error("删除任务失败:", error);
          ElMessage.error("删除任务失败，请重试");
        }
      })
      .catch(() => {});
  }
};

// 处理日历命令
const handleCalendarCommand = (command) => {
  console.log("日历视图:", command);
  ElMessage({
    message: `已切换到${command === "day" ? "日" : command === "week" ? "周" : "月"}视图`,
    type: "success",
  });
};

// 处理事件操作
const handleEventAction = async (command, event, index) => {
  if (command === "edit") {
    showEditEventDialog(event, index);
  } else if (command === "delete") {
    ElMessageBox.confirm("确定要删除这个日程吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        try {
          if (event.id) {
            await axios.delete(`/admin/calendar-events/${event.id}`);
          }
          calendarEvents.value.splice(index, 1);
          ElMessage.success("日程已删除");
        } catch (error) {
          console.error("删除日程失败:", error);
          ElMessage.error("删除日程失败，请重试");
        }
      })
      .catch(() => {});
  }
};

// 处理AI帮助
const handleAIHelp = () => {
  ElMessage({
    message: "AI助手可以帮您智能分析数据趋势和业务指标，提供决策支持",
    type: "info",
    duration: 5000,
  });
};

// 禁用日期
const disabledDate = (date) => {
  // 默认不禁用任何日期
  return false;
};

// 处理日期变化
const handleDateChange = async (date) => {
  console.log("日期变化:", date);
  
  // 如果选择了日期，并且有后端API，则尝试获取该日期的日程
  if (date) {
    try {
      const formattedDate = formatDate(date);
      const response = await axios.get(`/admin/calendar-events/date/${formattedDate}`);
      if (response && response.length > 0) {
        // 更新筛选后的日程
        calendarEvents.value = response;
      }
    } catch (error) {
      console.error("获取指定日期日程失败:", error);
      // 使用本地筛选
    }
  }
};

// 过滤日历事件
const filteredCalendarEvents = computed(() => {
  // 如果有选中日期，按日期过滤事件
  if (selectedDate.value) {
    const dateStr = formatDate(selectedDate.value);
    return calendarEvents.value.filter((event) => {
      // 如果事件有日期信息，则匹配；否则全部显示
      if (event.date) {
        return event.date === dateStr;
      }
      return true;
    });
  }
  return calendarEvents.value;
});

// 显示待办任务
const displayTodoTasks = computed(() => {
  if (todoTaskFilter.value === "pending") {
    return todoTasks.value.filter((task) => !task.completed);
  } else if (todoTaskFilter.value === "completed") {
    return todoTasks.value.filter((task) => task.completed);
  } else {
    return todoTasks.value;
  }
});

// 选择日期
const selectedDate = ref(new Date());

// 待办任务过滤器
const todoTaskFilter = ref("all");

// 初始化表单相关数据
const taskDialogVisible = ref(false);
const eventDialogVisible = ref(false);
const isEditingTask = ref(false);
const isEditingEvent = ref(false);
const taskSubmitting = ref(false);
const eventSubmitting = ref(false);
const taskFormRef = ref(null);
const eventFormRef = ref(null);
const currentTaskIndex = ref(-1);
const currentEventIndex = ref(-1);

// 任务表单
const taskForm = ref({
  title: "",
  priority: "中",
  deadlineDate: "",
  description: "",
  completed: false,
});

// 日程表单
const eventForm = ref({
  title: "",
  date: new Date(),
  startTime: "",
  endTime: "",
  location: "",
  color: "#1890ff",
  description: "",
});

// 表单验证规则
const taskRules = {
  title: [{ required: true, message: "请输入任务标题", trigger: "blur" }],
  priority: [{ required: true, message: "请选择优先级", trigger: "change" }],
  deadlineDate: [
    { required: true, message: "请选择截止日期", trigger: "change" },
  ],
};

const eventRules = {
  title: [{ required: true, message: "请输入日程标题", trigger: "blur" }],
  date: [{ required: true, message: "请选择日期", trigger: "change" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
};

// 显示添加任务对话框
const showAddTaskDialog = () => {
  isEditingTask.value = false;
  currentTaskIndex.value = -1;
  taskForm.value = {
    title: "",
    priority: "中",
    deadlineDate: "",
    description: "",
    completed: false,
  };
  taskDialogVisible.value = true;
};

// 显示编辑任务对话框
const showEditTaskDialog = (task, index) => {
  isEditingTask.value = true;
  currentTaskIndex.value = index;

  // 获取截止日期的日期时间格式
  let deadlineDate = "";
  if (task.deadline.includes("今天")) {
    deadlineDate = formatDate(new Date()) + task.deadline.split(" ")[1];
  } else if (task.deadline.includes("明天")) {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    deadlineDate = formatDate(tomorrow) + task.deadline.split(" ")[1];
  } else if (task.deadline.includes("后天")) {
    const dayAfterTomorrow = new Date();
    dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);
    deadlineDate = formatDate(dayAfterTomorrow) + task.deadline.split(" ")[1];
  } else if (task.deadline.includes("昨天")) {
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    deadlineDate = formatDate(yesterday) + task.deadline.split(" ")[1];
  } else {
    deadlineDate = task.deadline;
  }

  taskForm.value = {
    title: task.title,
    priority: task.priority,
    deadlineDate: deadlineDate,
    description: task.description || "",
    completed: task.completed,
  };

  taskDialogVisible.value = true;
};

// 提交任务表单
const submitTaskForm = async () => {
  if (!taskFormRef.value) return;

  await taskFormRef.value.validate(async (valid) => {
    if (valid) {
      taskSubmitting.value = true;

      try {
        // 格式化截止日期
        let deadline = "";
        const today = new Date();
        const taskDate = new Date(taskForm.value.deadlineDate);

        if (isSameDay(taskDate, today)) {
          deadline = `今天 ${taskForm.value.deadlineDate.split(" ")[1]}`;
        } else if (isSameDay(taskDate, tomorrow())) {
          deadline = `明天 ${taskForm.value.deadlineDate.split(" ")[1]}`;
        } else if (isSameDay(taskDate, dayAfterTomorrow())) {
          deadline = `后天 ${taskForm.value.deadlineDate.split(" ")[1]}`;
        } else if (isSameDay(taskDate, yesterday())) {
          deadline = `昨天 ${taskForm.value.deadlineDate.split(" ")[1]}`;
        } else {
          deadline = taskForm.value.deadlineDate;
        }

        const newTask = {
          title: taskForm.value.title,
          priority: taskForm.value.priority,
          deadline: deadline,
          description: taskForm.value.description,
          completed: taskForm.value.completed,
          deadline_date: new Date(taskForm.value.deadlineDate).toISOString()
        };

        if (isEditingTask.value && currentTaskIndex.value >= 0) {
          // 编辑现有任务
          const taskId = todoTasks.value[currentTaskIndex.value].id;
          if (taskId) {
            await axios.put(`/admin/tasks/${taskId}`, newTask);
          }
          todoTasks.value[currentTaskIndex.value] = {
            ...todoTasks.value[currentTaskIndex.value],
            ...newTask
          };
        } else {
          // 添加新任务
          if (process.env.NODE_ENV !== 'development') {
            const response = await axios.post("/admin/tasks", newTask);
            if (response && response.id) {
              newTask.id = response.id;
            }
          }
          todoTasks.value.unshift(newTask);
        }

        // 成功提示
        ElMessage({
          message: isEditingTask.value ? "任务已更新" : "任务已创建",
          type: "success",
        });

        taskDialogVisible.value = false;
      } catch (error) {
        console.error("提交任务失败:", error);
        ElMessage.error("操作失败，请重试");
      } finally {
        taskSubmitting.value = false;
      }
    }
  });
};

// 显示添加日程对话框
const showAddEventDialog = () => {
  isEditingEvent.value = false;
  currentEventIndex.value = -1;
  eventForm.value = {
    title: "",
    date: selectedDate.value || new Date(),
    startTime: "",
    endTime: "",
    location: "",
    color: "#1890ff",
    description: "",
  };
  eventDialogVisible.value = true;
};

// 显示编辑日程对话框
const showEditEventDialog = (event, index) => {
  isEditingEvent.value = true;
  currentEventIndex.value = index;

  // 解析事件时间
  const [startTime, endTime] = event.time.split(" - ");

  eventForm.value = {
    title: event.title,
    date: selectedDate.value || new Date(),
    startTime: startTime,
    endTime: endTime,
    location: event.location || "",
    color: event.color || "#1890ff",
    description: event.description || "",
  };

  eventDialogVisible.value = true;
};

// 提交日程表单
const submitEventForm = async () => {
  if (!eventFormRef.value) return;

  await eventFormRef.value.validate(async (valid) => {
    if (valid) {
      eventSubmitting.value = true;

      try {
        // 格式化时间
        const timeStr = `${eventForm.value.startTime}${eventForm.value.endTime ? " - " + eventForm.value.endTime : ""}`;

        const newEvent = {
          title: eventForm.value.title,
          time: timeStr,
          location: eventForm.value.location,
          color: eventForm.value.color,
          description: eventForm.value.description,
          date: formatDate(eventForm.value.date),
          event_date: new Date(eventForm.value.date).toISOString().split('T')[0],
          start_time: new Date(`${new Date(eventForm.value.date).toISOString().split('T')[0]}T${eventForm.value.startTime}:00`).toISOString(),
          end_time: eventForm.value.endTime ? new Date(`${new Date(eventForm.value.date).toISOString().split('T')[0]}T${eventForm.value.endTime}:00`).toISOString() : null
        };

        if (isEditingEvent.value && currentEventIndex.value >= 0) {
          // 编辑现有日程
          const eventId = calendarEvents.value[currentEventIndex.value].id;
          if (eventId) {
            await axios.put(`/admin/calendar-events/${eventId}`, newEvent);
          }
          calendarEvents.value[currentEventIndex.value] = {
            ...calendarEvents.value[currentEventIndex.value],
            ...newEvent
          };
        } else {
          // 添加新日程
          if (process.env.NODE_ENV !== 'development') {
            const response = await axios.post("/admin/calendar-events", newEvent);
            if (response && response.id) {
              newEvent.id = response.id;
            }
          }
          calendarEvents.value.push(newEvent);
        }

        // 成功提示
        ElMessage({
          message: isEditingEvent.value ? "日程已更新" : "日程已创建",
          type: "success",
        });

        eventDialogVisible.value = false;
      } catch (error) {
        console.error("提交日程失败:", error);
        ElMessage.error("操作失败，请重试");
      } finally {
        eventSubmitting.value = false;
      }
    }
  });
};

// 判断是否是同一天
const isSameDay = (d1, d2) => {
  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
};

// 获取明天日期
const tomorrow = () => {
  const date = new Date();
  date.setDate(date.getDate() + 1);
  return date;
};

// 获取后天日期
const dayAfterTomorrow = () => {
  const date = new Date();
  date.setDate(date.getDate() + 2);
  return date;
};

// 获取昨天日期
const yesterday = () => {
  const date = new Date();
  date.setDate(date.getDate() - 1);
  return date;
};

// 刷新监控数据
const refreshMonitorData = () => {
  ElMessage({
    message: "监控数据已刷新",
    type: "success",
  });

  // 模拟数据刷新
  monitorStats.value = {
    onlineUsers: Math.floor(Math.random() * 500) + 100,
    cpuUsage: Math.floor(Math.random() * 30) + 10,
    memoryUsage: Math.floor(Math.random() * 40) + 30,
    uptime: "3天 5小时 27分钟",
    todayVisits: (Math.floor(Math.random() * 500) + 1000).toLocaleString(),
  };

  // 刷新日志
  refreshLogs();
};

// 刷新日志数据
const refreshLogs = () => {
  // 模拟新的日志数据
  const newLog = {
    timestamp: new Date().toLocaleString(),
    type: ["警告", "信息", "错误", "成功"][Math.floor(Math.random() * 4)],
    ip: `192.168.1.${Math.floor(Math.random() * 255)}`,
    user: `用户${Math.floor(Math.random() * 10) + 1}`,
    action: ["登录系统", "修改配置", "查看报表", "导出数据", "添加用户"][
      Math.floor(Math.random() * 5)
    ],
    status: Math.random() > 0.2 ? "success" : "error",
  };

  // 添加到日志列表前面
  monitorLogs.value.unshift(newLog);
};

// 显示所有日志
const showAllLogs = () => {
  ElMessageBox.alert(
    '<div style="max-height: 400px; overflow-y: auto;"><pre>' +
      JSON.stringify(monitorLogs.value, null, 2) +
      "</pre></div>",
    "系统日志",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "关闭",
    },
  );
};

// 初始化图表相关变量
const sidebarPerformanceChartRef = ref(null);
const sidebarVisitsChartRef = ref(null);
let sidebarPerformanceChart = null;
let sidebarVisitsChart = null;

// 更新挂载生命周期函数，初始化侧边栏图表
onMounted(() => {
  try {
    // 加载待办任务和日程安排数据
    loadTodoTasks();
    loadCalendarEvents();
    
    // 初始化侧边栏监控图表
    nextTick(() => {
      if (sidebarPerformanceChartRef.value) {
        sidebarPerformanceChart = echarts.init(
          sidebarPerformanceChartRef.value,
        );
        updatePerformanceChart(sidebarPerformanceChart, true);
      }

      if (sidebarVisitsChartRef.value) {
        sidebarVisitsChart = echarts.init(sidebarVisitsChartRef.value);
        updateVisitsChart(sidebarVisitsChart, true);
      }
    });

    // 监听窗口大小变化
    window.addEventListener("resize", handleResize);
  } catch (error) {
    console.error("初始化图表失败:", error);
  }
});

// 修改卸载函数，清理所有图表实例
onUnmounted(() => {
  if (chartInstances) {
    Object.values(chartInstances).forEach((chart) => {
      if (chart) chart.dispose();
    });
  }

  if (sidebarPerformanceChart) {
    sidebarPerformanceChart.dispose();
  }

  if (sidebarVisitsChart) {
    sidebarVisitsChart.dispose();
  }

  window.removeEventListener("resize", handleResize);
});

// 添加侧边栏监控图表函数
const updatePerformanceChart = (chart, isSmall = false) => {
  const option = {
    grid: {
      top: isSmall ? 20 : 30,
      bottom: isSmall ? 30 : 50,
      left: isSmall ? 50 : 80,
      right: isSmall ? 20 : 30,
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      show: !isSmall,
      bottom: 10,
      data: ["CPU使用率", "内存使用率"],
    },
    xAxis: {
      type: "category",
      data: ["00:00", "04:00", "08:00", "12:00", "16:00", "20:00", "23:59"],
      axisLabel: {
        fontSize: isSmall ? 10 : 12,
      },
    },
    yAxis: {
      type: "value",
      name: isSmall ? "" : "使用率(%)",
      axisLabel: {
        fontSize: isSmall ? 10 : 12,
      },
    },
    series: [
      {
        name: "CPU使用率",
        type: "line",
        smooth: true,
        data: [10, 12, 25, 35, 30, 40, 20],
        itemStyle: {
          color: "#1890ff",
        },
      },
      {
        name: "内存使用率",
        type: "line",
        smooth: true,
        data: [30, 35, 40, 50, 60, 55, 45],
        itemStyle: {
          color: "#52c41a",
        },
      },
    ],
  };

  chart.setOption(option);
};

const updateVisitsChart = (chart, isSmall = false) => {
  const option = {
    grid: {
      top: isSmall ? 20 : 30,
      bottom: isSmall ? 30 : 50,
      left: isSmall ? 50 : 80,
      right: isSmall ? 20 : 30,
    },
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      axisLabel: {
        fontSize: isSmall ? 10 : 12,
      },
    },
    yAxis: {
      type: "value",
      name: isSmall ? "" : "访问量",
      axisLabel: {
        fontSize: isSmall ? 10 : 12,
      },
    },
    series: [
      {
        name: "访问量",
        type: "bar",
        data: [120, 132, 101, 134, 90, 230, 210],
        itemStyle: {
          color: "#1890ff",
        },
      },
    ],
  };

  chart.setOption(option);
};

// ... existing code ...

// 地图设置相关
const showMapSettings = ref(false);

// 重置地图配置
const resetMapConfig = () => {
  mapConfig.china = {
    zoom: 1.2,
    layoutCenter: [500, 350],
    layoutSize: 700,
  };
  mapConfig.guangxi = {
    zoom: 1.1,
    layoutCenter: [400, 250],
    layoutSize: 450,
  };

  // 使用setTimeout确保配置应用后再更新地图
  setTimeout(() => {
    updateRegionMap();
  }, 100);
};

// 图表实例集合
const chartInstances = reactive({});

// 监控地图配置变化
watch(
  () => JSON.stringify(mapConfig),
  () => {
    nextTick(() => {
      updateRegionMap();
    });
  },
);

// 更新地图大小
const updateMapSize = (size) => {
  if (!regionType.value) return;

  // 更新当前显示地图类型的大小
  mapConfig[regionType.value].layoutSize = size;

  // 延迟更新，确保能正确应用
  setTimeout(() => {
    updateRegionMap();
  }, 100);
};

// 监听地图类型变化
watch(
  regionType,
  (newType) => {
    // 确保在地图类型变化时应用正确的配置
    nextTick(() => {
      updateRegionMap();
    });
  },
  { immediate: true },
);

// 定义 handleResize 函数
const handleResize = () => {
  try {
    // 调整所有图表大小
    Object.values(chartInstances).forEach((chart) => {
      if (chart && !chart.isDisposed()) {
        chart.resize();
      }
    });
  } catch (error) {
    console.error("调整图表大小时出错:", error);
  }
};
</script>

<style lang="scss" scoped>
.admin-dashboard {
  padding: 20px;
  color: var(--el-text-color-primary);
  background-color: var(--el-bg-color);
}

.welcome-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #1890ff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
  gap: 16px;
}

.welcome-left {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 16px;
  min-width: 240px;
  max-width: 280px;
}

.user-greeting {
  display: flex;
  align-items: center;
  gap: 14px;
}

.user-avatar {
  :deep(.el-avatar) {
    border: 3px solid rgba(255, 255, 255, 0.3);
  }
}

.welcome-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.welcome-greeting {
  font-size: 16px;
  font-weight: 500;

  .date {
    font-size: 14px;
    opacity: 0.8;
    margin-top: 4px;
  }
}

.weather-section {
  flex: 1;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 12px;
  max-width: 350px;
  margin: 0 auto;
}

.weather-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.weather-icon {
  width: 42px;
  height: 42px;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;

  i {
    color: #ffd700;
  }
}

.weather-info {
  flex: 1;
}

.city-temp {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;

  .city {
    font-size: 14px;
    opacity: 0.8;
  }

  .temperature {
    font-size: 18px;
    font-weight: 600;
  }
}

.forecast-row {
  display: flex;
  justify-content: space-between;
}

.day-forecast {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;

  .day {
    font-size: 11px;
    opacity: 0.8;
  }

  i {
    font-size: 14px;

    &.fa-sun {
      color: #ffd700;
    }

    &.fa-cloud-sun {
      color: #f0f0f0;
    }

    &.fa-cloud {
      color: #e0e0e0;
    }

    &.fa-cloud-showers-heavy {
      color: #c0c0c0;
    }
  }

  .temp {
    font-size: 11px;
    font-weight: 500;
  }
}

.stat-items {
  display: flex;
  align-items: center;
  padding-top: 4px;
}

.stat-item {
  margin-right: 16px;

  .stat-label {
    font-size: 13px;
    opacity: 0.8;
    margin-bottom: 4px;
  }

  .stat-value {
    font-size: 16px;
    font-weight: 600;
  }
}

.stat-divider {
  width: 1px;
  height: 24px;
  background-color: rgba(255, 255, 255, 0.2);
  margin: 0 16px 0 0;
}

.action-area {
  display: flex;
  flex-direction: row;
  gap: 8px;
  min-width: 120px;

  .action-button {
    background-color: rgba(255, 255, 255, 0.15);
    border-color: rgba(255, 255, 255, 0.3);
    color: white;

    &:hover {
      background-color: rgba(255, 255, 255, 0.25);
      border-color: rgba(255, 255, 255, 0.4);
      color: white;
    }
  }
}

@media screen and (max-width: 1200px) {
  .welcome-card {
    flex-wrap: wrap;
    gap: 20px;
    padding: 20px;

    .welcome-left {
      min-width: 220px;
      width: auto;
      max-width: none;
    }

    .weather-section {
      min-width: 220px;
      flex: 1;
      max-width: none;
      margin: 0;
    }

    .action-area {
      flex-direction: row;
      width: 100%;
      justify-content: flex-end;
      margin-top: 10px;
    }
  }
}

@media screen and (max-width: 768px) {
  .welcome-card {
    padding: 16px;

    .welcome-left {
      width: 100%;
    }

    .weather-section {
      width: 100%;
    }

    .action-area {
      justify-content: center;
    }
  }

  .stat-items {
    justify-content: flex-start;
    width: 100%;
  }
}

@media screen and (max-width: 576px) {
  .welcome-card {
    flex-direction: column;
    align-items: flex-start;

    .action-area {
      flex-direction: column;
      width: 100%;
      gap: 8px;

      .action-button {
        width: 100%;
      }
    }
  }

  .user-greeting {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .stat-items {
    flex-wrap: wrap;

    .stat-item {
      margin-right: 24px;
      margin-bottom: 12px;
    }

    .stat-divider {
      display: none;
    }
  }
}

.statistics-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  overflow: hidden;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  }

  :deep(.el-card__body) {
    background-color: transparent;
    padding: 16px !important;
  }
}

.card-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.card-main {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.card-trend {
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;

  &.up {
    color: #52c41a;
  }

  &.down {
    color: #f5222d;
  }

  i {
    font-size: 12px;
  }
}

.card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  font-size: 24px;

  i {
    font-size: 22px;
  }
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);

  .footer-label {
    font-size: 13px;
    color: rgba(0, 0, 0, 0.45);
  }

  .footer-value {
    font-size: 14px;
    font-weight: 500;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--el-bg-color);

  .header-left {
    display: flex;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: var(--el-text-color-primary);
    }

    .ml-2 {
      margin-left: 8px;
    }
  }
}

.ranking-list {
  .ranking-item {
    display: flex;
    align-items: center;
    padding: 12px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    transition: all 0.3s;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: var(--el-fill-color-light);
    }

    .ranking-index {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background-color: var(--el-text-color-secondary);
      color: var(--el-color-white);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;
      font-size: 14px;

      &.top-3 {
        background-color: var(--el-color-warning);
      }
    }

    .ranking-image {
      width: 48px;
      height: 48px;
      border-radius: 8px;
      margin-right: 12px;
    }

    .ranking-info {
      flex: 1;

      .name {
        font-size: 14px;
        font-weight: bold;
        color: var(--el-text-color-primary);
        margin-bottom: 4px;
      }

      .stats {
        font-size: 12px;
        color: var(--el-text-color-secondary);

        span {
          margin-right: 12px;
        }
      }
    }

    .ranking-trend {
      font-size: 14px;
      font-weight: bold;

      &.up {
        color: var(--el-color-success);
      }

      &.down {
        color: var(--el-color-danger);
      }
    }
  }
}

.notification-content {
  .notification-title {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 4px;
    color: var(--el-text-color-primary);

    &.unread {
      color: var(--el-color-primary);

      &::before {
        content: "";
        display: inline-block;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: var(--el-color-primary);
        margin-right: 6px;
      }
    }
  }

  .notification-desc {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.monitor-stats {
  display: flex;
  gap: 24px;

  .stat-item {
    display: flex;
    align-items: center;
    gap: 8px;

    .label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }

    .value {
      font-size: 14px;
      font-weight: bold;
      color: var(--el-color-primary);
    }
  }
}

.mt-4 {
  margin-top: 24px;
}

.ml-2 {
  margin-left: 8px;
}

.monitor-tabs {
  margin-top: 20px;
}

.inline-progress {
  width: 120px;
  margin-left: 8px;
}

.sales-analysis {
  margin-bottom: 20px;

  .metric-card {
    background: var(--el-fill-color-light);
    border-radius: 8px;
    padding: 16px;
    height: 140px;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    }

    .metric-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
    }

    .metric-icon {
      width: 36px;
      height: 36px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;

      i {
        font-size: 16px;
      }
    }

    .metric-trend {
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 4px;

      &.up {
        color: #52c41a;
      }

      &.down {
        color: #f5222d;
      }

      i {
        font-size: 10px;
      }
    }

    .metric-title {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      margin-bottom: 8px;
    }

    .metric-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 12px;
    }

    .metric-chart {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 40px;
    }
  }
}

.chart-wrapper {
  .chart-header {
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: bold;
    color: var(--el-text-color-primary);
  }
}

// 优化间距和阴影
.mt-4 {
  margin-top: 24px;
}

.el-card {
  transition: all 0.3s;
  background-color: var(--el-bg-color);
  border-color: var(--el-border-color-lighter);

  &:hover {
    box-shadow: var(--el-box-shadow-light);
  }

  :deep(.el-card__header) {
    background-color: var(--el-bg-color);
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
}

// 图表主题适配
:deep(.echarts) {
  background-color: var(--el-bg-color) !important;
}

// 响应式布局
@media screen and (max-width: 1400px) {
  .statistics-card {
    margin-bottom: 16px;
  }

  .chart-container {
    height: 300px;
  }
}

@media screen and (max-width: 992px) {
  .welcome-card {
    flex-direction: column;

    .welcome-card-content {
      flex-direction: column;
      align-items: flex-start;
      gap: 24px;
    }

    .welcome-right {
      width: 100%;

      .action-buttons {
        width: 100%;
        justify-content: flex-start;
      }
    }
  }
}

@media screen and (max-width: 576px) {
  .welcome-left {
    flex-direction: column;
    align-items: flex-start;
  }

  .user-stats {
    width: 100%;
    justify-content: space-between;
  }
}

// 数据概览卡片样式
.data-overview-card {
  height: 140px;

  :deep(.el-card__body) {
    padding: 16px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .overview-header {
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;
  }

  .overview-title {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    margin-bottom: 8px;
  }

  .overview-value {
    display: flex;
    align-items: baseline;

    .number {
      font-size: 24px;
      font-weight: bold;
      color: var(--el-text-color-primary);
      margin-right: 8px;
    }

    .trend {
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 4px;

      &.up {
        color: #52c41a;
      }

      &.down {
        color: #f5222d;
      }

      i {
        font-size: 10px;
      }
    }
  }

  .overview-chart {
    flex: 1;
    width: 100%;
  }
}

// 侧边栏样式
.sidebar-card {
  margin-bottom: 0;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-weight: 600;
      font-size: 16px;
    }
  }

  .workspace-content {
    padding: 0;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .section-stats {
      display: flex;
      align-items: center;
    }

    .today-date {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }

  .todo-list {
    .todo-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);

      &:last-child {
        border-bottom: none;
      }

      .todo-item-left {
        display: flex;
        align-items: center;
        flex: 1;
        min-width: 0;
      }

      .todo-info {
        margin-left: 12px;
        flex: 1;
        min-width: 0;

        .todo-title {
          font-weight: 500;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .todo-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }

        .todo-deadline {
          display: flex;
          align-items: center;
        }

        &.completed {
          .todo-title {
            text-decoration: line-through;
            color: var(--el-text-color-secondary);
          }
        }
      }
    }
  }

  .calendar-header {
    margin-bottom: 12px;
  }

  .calendar-event {
    position: relative;
    display: flex;
    flex-direction: column;
    padding: 12px 12px 12px 16px;
    margin-bottom: 8px;
    background-color: var(--el-fill-color-lighter);
    border-radius: 6px;
    border-left: 4px solid transparent;
    overflow: hidden;

    .event-time {
      display: flex;
      align-items: center;
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 6px;
      gap: 6px;
    }

    .event-content {
      display: flex;
      flex-direction: column;
      flex: 1;
      min-width: 0;
    }

    .event-title {
      font-weight: 500;
      margin-bottom: 4px;
    }

    .event-location {
      display: flex;
      align-items: center;
      font-size: 12px;
      color: var(--el-text-color-secondary);
      gap: 4px;
    }

    .event-actions {
      position: absolute;
      top: 10px;
      right: 10px;
    }

    .event-indicator {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 4px;
    }
  }

  .assistant-container {
    display: flex;
    gap: 12px;
    padding: 12px;
    background-color: var(--el-fill-color-lighter);
    border-radius: 8px;

    .assistant-avatar {
      display: flex;
      align-items: flex-start;

      .assistant-icon {
        background-color: var(--el-color-primary-light-7);
        color: var(--el-color-primary);
        font-size: 20px;
      }
    }

    .assistant-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .assistant-message {
      font-size: 14px;
      line-height: 1.5;
    }

    .assistant-actions {
      display: flex;
      gap: 8px;
    }
  }

  // 侧边栏监控样式
  .sidebar-monitor-stats {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;

      .label {
        color: var(--el-text-color-secondary);
      }

      .value {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .inline-progress {
        width: 150px;
      }
    }
  }

  .sidebar-monitor-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 10px;
    }

    :deep(.el-tabs__nav) {
      transform: scale(0.9);
      transform-origin: left;
    }
  }

  .log-item {
    padding: 8px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);

    &:last-child {
      border-bottom: none;
    }

    .log-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 4px;

      .log-time {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }

    .log-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 13px;

      .log-user {
        color: var(--el-text-color-secondary);
        font-size: 12px;
      }

      .log-action {
        flex: 1;
        margin: 0 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .view-more-link {
    text-align: center;
    padding: 10px 0;
    font-size: 13px;
  }
}

.ml-1 {
  margin-left: 4px;
}

.ml-2 {
  margin-left: 8px;
}

.mt-2 {
  margin-top: 8px;
}

.mt-3 {
  margin-top: 12px;
}

.mt-4 {
  margin-top: 16px;
}

.mx-2 {
  margin-left: 8px;
  margin-right: 8px;
}

@media screen and (max-width: 768px) {
  .welcome-card {
    flex-direction: column;
    align-items: flex-start;
  }

  .user-stats {
    width: 100%;
    justify-content: space-between;
  }
}

.map-settings-panel {
  background-color: var(--el-bg-color-overlay);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--el-border-color-light);
  transition: all 0.3s ease;
  animation: fadeIn 0.3s ease;

  .settings-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    color: var(--el-text-color-primary);
    border-bottom: 1px solid var(--el-border-color-lighter);
    padding-bottom: 8px;
  }

  .settings-row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .settings-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      width: 90px;
      flex-shrink: 0;
    }

    .el-slider {
      flex: 1;
      margin: 0 10px;
    }

    .el-input-number {
      width: 80px;
      flex-shrink: 0;
    }
  }

  .settings-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid var(--el-border-color-lighter);

    .el-button {
      margin-left: 16px;
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.ai-response-container {
  max-height: 250px;
  overflow-y: auto;
  border-radius: 4px;
  padding-right: 5px;
}

.ai-response-text {
  white-space: pre-wrap;
  word-break: break-word;
  margin: 0;
}
</style>
